David Sacco David Sacco - 1 year ago 72
Swift Question

Replace exactly one pixel in an image and put it in another image via Swift

Simply put, if I have an image,

and another image
, I want to replace the RGB value at a position
and assign that pixel to
. How might I do this in Core Image, or using a custom kernel?

This seems like it might not be an easy thing to do, considering the way Core Image works. However, I was wondering maybe there was a way to extract the value of the pixel at
, create an image
as large as
with just that pixel, and then overlay
only at that one point. Just an idea, hopefully there's a better way.

Answer Source

If you want to set just one pixel, you can create a small color kernel that compares a passed target coordinate with the current coordinate and colors the output appropriately. For example:

let kernel = CIColorKernel(string:
"kernel vec4 setPixelColorAtCoord(__sample pixel, vec2 targetCoord, vec4 targetColor)" +
    "{" +
    "   return int(targetCoord.x) == int(destCoord().x) && int(targetCoord.y) == int(destCoord().y) ? targetColor : pixel; " +

Then, given an image, let's say a solid red:

let image = CIImage(color: CIColor(red: 1, green: 0, blue: 0))
    .imageByCroppingToRect(CGRect(x: 0, y: 0, width: 640, height: 640))

If we want to set the pixel at 500, 100 to blue:

let targetCoord = CIVector(x: 500, y: 100)
let targetColor = CIColor(red: 0, green: 0, blue: 1)

The following will create a CIImage named final with a single blue pixel in a sea of red:

let args = [image, targetCoord, targetColor]
let final = kernel?.applyWithExtent(image.extent, arguments: args)

If you want to draw more than one pixel, this may not be the best solution though.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download