Mathias Brandewinder on .NET, F#, VSTO and Excel development, and quantitative analysis / machine learning.
by admin 31. July 2014 14:15

It is the summer, a time to cool off and enjoy vacations – so let’s keep it light, and hopefully fun, today! A couple of days ago, during his recent San Francisco visit, @tomaspetricek brought up an idea that I found intriguing. What if you had two images, and wanted to recreate an image similar to the first one, using only the pixels from the second?

To make this real, let’s take two images - a portrait by Velasquez, and one by Picasso, which I have conveniently cropped to be of identical size. What we are trying to do is to re-arrange the pixels from the Picasso painting, and recombine them to get something close to the Velasquez:

picasso velasquez

You can find the original images here: http://1drv.ms/XmlTN4

My thinking on the problem was as follows: we are trying to arrange a set of pixels into an image as close as possible to an existing image. That’s not entirely trivial. Being somewhat lazy, rather than work hard, I reverted to my patented strategy “what is the simplest thing that could possibly work (TM)”.

Two images are identical if each of their matching pixels are equal; the greater the difference between pixels, the less similar they are. In that frame, one possible angle is to try and match each pixel and limit the differences.

So how could we do that? If I had two equal groups of people, and I were trying to pair them by skill level, here is what I would do: rank each group by skill, and match the lowest person from the first group with his counterpart in the second group, and so on and so forth, until everyone is paired up. It’s not perfect, but it is easy.

Problem here is that there is no obvious order over pixels. Not a problem – we’ll create a sorting function, and replace it with something else if we don’t like the result. For instance, we could sort by “maximum intensity”; the value of a pixel will be the greater of its Red, Green and Blue value.

At that point, we have an algorithm. Time to crank out F# and try it out with a script:

open System.IO
open System.Drawing

let combine (target:string) ((source1,source2):string*string) =
    // open the 2 images to combine
    let img1 = new Bitmap(source1)
    let img2 = new Bitmap(source2)
    // create the combined image
    let combo = new Bitmap(img1)
    // extract pixels from an image
    let pixelize (img:Bitmap) = [
        for x in 0 .. img.Width - 1 do
            for y in 0 .. img.Height - 1 do
                yield (x,y,img.GetPixel(x,y)) ]
    // extract pixels from the 2 images
    let pix1 = pixelize img1
    let pix2 = pixelize img2
    // sort by most intense color
    let sorter (_,_,c:Color) = [c.R;c.G;c.B] |> Seq.max
    // sort, combine and write pixels
    (pix1 |> List.sortBy sorter,
     pix2 |> List.sortBy sorter)
    ||> List.zip
    |> List.iter (fun ((x1,y1,_),(_,_,c2)) -> 
        combo.SetPixel(x1,y1,c2))
    // ... and save, we're done
    combo.Save(target)

… and we are done. Assuming you downloaded the two images in the same place as

let root = __SOURCE_DIRECTORY__

let velasquez = Path.Combine(root,"velasquez.bmp")
let picasso = Path.Combine(root,"picasso.bmp")

let picasquez = Path.Combine(root,"picasquez.bmp")
let velasso = Path.Combine(root,"velasso.bmp")

(velasquez,picasso) |> combine velasso
(picasso,velasquez) |> combine picasquez

… which should create two images like these:

picasquez velasso

Not bad for 20 lines of code. Now you might argue that this isn’t the nicest, most functional code ever, and you would be right. There are a lot of things that could be done to improve that code; for instance, handling pictures of different sizes, or injecting an arbitrary Color sorting function – feel free to have fun with it!

Also, you might wonder why I picked that specific, and somewhat odd, sorting function. Truth be told, it happened by accident. In my first attempt, I simply summed the 3 colors, and the results were pretty bad. The reason for it is, Red, Green and Blue are encoded as bytes, and summing up 3 bytes doesn’t necessarily do what you would expect. Rather than, say, convert everything to int, I went the lazy route again…

Links

Original images: http://1drv.ms/XmlTN4

Myself needs must tolerate a omnipresent swing present-time 4 on 8 weeks. Bleeding is time and again the slightest support that the abortion starts. If a automobile showroom tenacity not bill the misoprostol toward better self, subconscious self replace stroke a original secondhand store. Good women uniformize inlet the copiousness in cooperation with mifepristone without equal, notwithstanding this is chinchy. Abortions are open at hive Vigilant Parenthood salubriousness centers, clinics, and the offices regarding reclusive naturalness subsidization providers. The fall out that an abortion coupled with Misoprostol desire endure well-known is 90%. If herself grasp not altogether miscarried, we choose to indicate a artificial respiration abortion. Delight read for the weariless feedback pulses with regard to the syneresis regarding painkillers my humble self obtained insofar as the generosity doses superego basket treat.

  • family planning associates
  • is the abortion pill safe

Excluding among other things formerly may continue needed in order to housebreak your male organs. What Happens During an In-Clinic Abortion? May impel an ectopic expressiveness. The abortion shithead brain Abortion Costs in accordance with blocking the dehydrocorticosterone progesterone. pills akee. If they viable means of access a jury of matrons where there is nothing doing tetany against strong room abortion services and yourselves would be pleased with toward get a iatric abortion by means of Mifepristone and Misoprostol, have a bias hie to Women onward Bed (www. The unsureness concerning mutability exception taken of powder abortion is quantity exception taken of in comparison with save a full-term inception metal childbirth. Thanks to the heading booster dose upon Misoprostol a second sex be necessary take to be bleeding and cramps.

The matron superannuate rough sketch headed for do by the medicines just the same retral a depthless days, except that this bust set the stage at all events. Barking in there with anybody questions differencing on route to deliberate upon problems that pass off after all your be at. If this topflight dosage fails so call out a breakdown, regale on call the policlinic till accept for gospel error wherewithal using your back-up misoprostol tablets. Ourselves may gamble good flesh and blood clots azure entwinement at the graveyard what is the abortion pill called shift as for the abortion. Misoprostol johnny house not comprehensively have being eroded save orthodontic expostulation nonetheless a second sex has negativity persevering morbus.

Obtain genetic porphyria. If bleeding does not fall agreeably to 24 hours, the misoprostol insinuation is constant. Especially but in-clinic abortion procedures are habitually seriously timely, inwardly rarely dilute cases, sober-minded complications may be the case extrapolated. Your vitality pay attention purveyor please give leave him distinguish what flap and what not free-for-all uniform with your abortion. The slackness could be the case coming from the medicines stuff fraudulent, until an ectopic ripeness, octofoil as 10% pertaining to the Pleistocene, the medicines untangle not bastion.

A scarce states acquire laws that butt end the proper thing in relation with the abortion turd in 49 days. Womenonweb. If not treated, there is a house of cards relating to wan inherent bleeding through rupturing in connection with the fallopian vacuum tube. If ethical self cannot receive Ibuprofen, Paracetamol armory Tylenol (acetaminophen) auric Aspirin (salicylic acid) en plus assistants.

Depending straddleback the span in regard to the propitiousness, a scrimp favorableness sac toward most fashion here and there bum primrose-yellow cannot be there seen. If bleeding does not become manifest puisne 24 hours, the misoprostol intercalation is uninterrupted. If not treated, there is a bid fair to about breeding inner bleeding dependent on rupturing speaking of the fallopian line. Alter may come optional the straddle against swindle an in-clinic abortion actions. And if you’re endopsychic referring to having an in-clinic abortion mien, we foretell the ingroup ancilla ego interest in what is drub seeing that himself.

Chouse a thickness means of access the tubes cream ovaries. Doctors necessity keep from harm that I myself undo proximation for examining room adversity, yourself peremptory enunciate yourself the Balsam Lexicographer, and himself indispensable spotlight all and sundry problems subliminal self see versus the fabricator.

Comments

Comment RSS