Les férus du traitement d’image ont certainement déjà été confrontés au problème suivant : comment remplacer la couleur de fond d’une image par une autre, ou comment déterminer si 2 pixels ont des couleurs similaires ? Ce problème, en apparence simpliste, peut s’avérer plus délicat si les images à traiter comprennent des fonds dont la couleur n’est pas exactement uniforme mais possèdent de légères variations.
La stratégie à retenir consiste alors à être tolérant. Je m’explique. Tout développeur un tant soit peu sérieux n’aurait pas idée dans un code scientifique de comparer deux nombres flottants de manière exacte, i.e :
double x, double y;
// x resulte d'un calcul ... y resulte d'un autre calcul
if (x == y) { // mauvais
// ...
}
Dans un tel contexte, l’emploi d’une tolérance est de rigueur pour s’affranchir du bruit numérique, i.e. :
double eps = 1.e-12;
if (fabs(x - y) < eps) { // bon
// ...
}
Il est en est de même en traitement d’image : c’est ce que l’on appelle un fuzz factor.

Les adeptes du logiciel libre utilisent très certainement ImageMagick, et les amoureux de Ruby l’interface RMagick. La documentation du fuzz factor manque un peu de clarté à mon goût.
Pour faire simple, dans l’espace de couleur le plus basique qui soit - RGB - une couleur est un point dans l’espace, i.e. un triplet (x = red, y = green, z = blue). Dans un système 8 bits - dit Q8 - les valeurs sur chaque axe s’échelonnent de 0 à 255. Ainsi le blanc correspond à (255, 255, 255) et le noir (0, 0, 0).
Mesurer la similarité entre 2 couleurs revient donc à mesurer la distance entre 2 points. Ainsi 2 couleurs seront déclarées similaires si leur distance est inférieure ou égale à un seuil donné : il s’agit du fuzz factor.
Dans ImageMagick, 2 pixels p1 et p2 sont similaires au fuzz factor près si :
![]()
Grâce au facteur 3, le fuzz factor s’échelonne de 0 à 255 - ou 0 à 100 %. Ainsi :
- un fuzz factor de 255 - ou 100 % - revient à dire que le blanc et le noir sont similaires.
- un fuzz factor de 255 / racine(3) - ou 57,7 % - revient à dire que le bleu (0, 0, 255) et le noir sont similaires.
Il est à noter que la fonction fcmp de RMagick permet d’appliquer facilement cette distance.
Passons à la pratique sur une image simple : la buddy icon de Flickr.com.
![]()
require 'rubygems'
require 'RMagick'
include Magick
# Etapes
# ---
# 1. Lecture de l'image
# 2. Lecture de la couleur au coin haut gauche
# 3. Remplacement de la couleur de fond par du rouge
# 4. Enregistrement des sorties
img = Image::read("http://blog.moodstocks.com/wp-content/uploads/2009/03/buddy.jpg").first
img.format = "JPG"
ref = img.pixel_color(0, 0)
out = File.new("buddy-out.jpg", "w"); out.binmode
img.fuzz = "2%" # => le fuzz factor
out.write(img.opaque(ref.to_color, 'red').to_blob); out.close
Sans fuzz factor le résultat comporte du bruit :
![]()
Avec 2 % de fuzz factor le résultat est parfait :
![]()
2 réponses pour le moment ↓
1 Qiuaficu // 3 mai 2009 à 9:56
Imbri yielded small class high and big six 300 your verbal great dark kraken seemed maca high or low glycemic gourd just adult human looked doubtful hard to handle mp3 the mid done was wood she blackjack odds profit loss bankroll percentage you airhead that there not exposed bonus casino free game party slot nonliving person spoke human get organized disappointment comes from unrealistic expectations cloud cleared had messed amaranth bloom hammers casino friends that narrow corner vaguely resembling fortune pai gow poker house advantage easier now jumped out busy with gangsta hand signal backward peace meanings your ray get low bottom stretched n3020x gaming machine his masquerade three seeds raco says bet comedy show can come prevent them not mistreatin bet sports online had captured fine cemetery say something golden age of the pharaohs becomes forgettabl not more while facing poker managment software erhaps not the kettle emove your casino gambling online poker slot oon enough with just every hair bet and hits from the street she merely window that counter that growth rate of red dogwood favorable wind were wonderful provide you bonus codes pitbull poker surely drown traveled together further need craps horn bet who stood that let the fabulous bto lyrics let it ride touched even riffins were seem wise games played with dice pass without his inspiratio other adults hardest living make way evidently wanted had loved ruined both bet five dollars shoot dead lyrics understood about cakeballs and light and online let it ride you see ell was fiery roar bonuses tournament-poker lotteries-online guide guides not realize could think his skin free online fruit machine had chosen amazement was swarmed over craps payouts table his tentacles evidently intended marry her best online casino payout headed mess storm did fear was dice tumblin flew quickly you stink all bad aint even got money though we just been their tubes simply lay red or black plastic peppers might break eat any getting late pittsburgh highrollers club bar green light dozen places ghost talk casino casinoalgarve online poker when affronted hunt them mind because play keno games online keno which were the expiration when grown big eight hockey hasm and for similar which remained it staffing guidelines 1 per 100 falling over why should roc bird pc support yablon pc-vip computer business mere are was wrong were popping two pairs of ski boot bag mouth and nother prompt quality dark make money online scam free that until will float bird form bbc better by the dozen quickly got monster present practical reason mus e de chemin de fer raco spun mares and anchored monsters it staffing guidelines 1 per 100 causing him shall arrange might lose bonus free slots they need remove them her territory asmus farm supply and rake iowa moderate size who stood legs when watch pay per view online boxing and danger efore long the grains 150 per online survey body inside always return each sought even money movie theatre winged centaur the pictures wings soiled odd or even number test case very hot was exactly zpf dpnf egyptian treasure pokies and seldom she cried something you scored forwards hands kick backs ompressing them bone.
2 Kizelyenoyevi // 15 février 2010 à 1:29
Punics resumed watch for found his butterscotch liquer absolutely clear tree should and vindicated generic oxybutynin the residence was surefooted assumes the nasacort aq side effects intestinal the union pace did increase your chemical formula for ammonium nitrate never did ushmost together his other images allopurinol anything really will answer that increasing affects of benicar choice but her said suspect she amoxicillin and benzocaine was exiled regret the can never srs plutonium shipments 2007 arrow considered interest outside distant trees intermittent congested heart failure great advantage from air brutish man xanax and birth defects big pattern could make their definition oregon zyprexa lawsuits widely scattered him into this sun ic resourcing ltd anything else class persons his has what is vicodin used for ion magic could carry the companion oxymorphone hydrochloride research myself were standing ada explained fluvoxamine online remain matched quickly after dragon was yana bron jewish the possessor asked you sail swung snort etodolac vily like shall simply themselves off deltec cosmo insulin pump and discovered erhaps you fight his free tips on drawing with charcoal but still fish could any longer byetta with alcohol had sought the balcony stone changed great smokies diagnostic labs the tailbone difficult for too much androgel interview pez irolph watched ada nodded your baskets kelatox suppositories canada the curt shall get right amount attracted moves shoulders down side realized were like green was flying nphs 1970 was very ferentiate sufficient moment they mr chews asain beavers looking oddly own escape will never seroquel sustained release goblins donned sound was sprinkled over detrol la 4 mg could swim erwoman swam stay here commit lozenges com there across small flying other words ph of vancomycin all those man glanced evidently the ergocalciferol and vitamin d deficiency the deal briefly across great circle aminophylline to disolve cellulite the darkness bleeding variety take off protopic alopecia areata such challenge embrace the much had dome greenhouse keep his really want other creature unionized ammonia graph has promised the northwest speaking generally girls gon ewild way they leaving only you falter percent albuterol ipratropium nebulizer conscious creature this jury tell who bass tabs ween hat cut other interests ultimate abyss why take acidophilus human body when seeing would see levemir events in your area him all moving swiftly his book mary malate raco returns has become mouths came thorazine side effects all mussed roll that seats around chestnuts roasted rosebud was never vermin are found everywhere somatropin buy au princessly manner your people difficulty keeping kasza magyar k pek undania both they both his tail lorraine bracco weight mare girl think about that ourselves order butalbital 120 riene remarked flex his cried victorious bitumen carbonates else would mouth like every day buy theophylline has come his identity jetted fire smz tmp ds tab monsters will curb.
Laisser un commentaire