精确替换图像中的一个像素,然后通过Swift将其放置在另一图像中 [英] Replace exactly one pixel in an image and put it in another image via Swift

查看:127
本文介绍了精确替换图像中的一个像素,然后通过Swift将其放置在另一图像中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地说,如果我有一张图像, I 和另一张图像 J ,我想替换RGB位置 I(t,s)的值,并将该像素分配给 J(t,s)



考虑到Core Image的工作方式,这似乎并不容易。但是,我想知道也许有一种方法可以提取(t,s)处的像素值,创建图像 K J 一样大,仅带有该像素,然后将 J 覆盖到 K 仅在这一点上。只是一个想法,希望有更好的方法。

解决方案

如果您只想设置一个像素,您可以创建一个较小的颜色内核,该内核将传递的目标坐标与当前坐标进行比较,并对输出进行适当的着色。例如:

  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:像素; +
}

然后,给定一个图像,让我们说一个纯红色:

  let image = CIImage(color:CIColor(red:1 ,绿色:0,蓝色:0))
.imageByCroppingToRect(CGRect(x:0,y:0,宽度:640,高度:640))

如果我们要将像素设置为500,则将100设置为蓝色:

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


以下将创建名为 final CIImage 在红色的海洋中有一个蓝色的像素:

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

如果要绘制多个像素,这可能不是最佳解决方案。



Simon


Simply put, if I have an image, I and another image J, I want to replace the RGB value at a position I(t,s) and assign that pixel to J(t,s). 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 (t,s), create an image K as large as J with just that pixel, and then overlay J with K only at that one point. Just an idea, hopefully there's a better way.

解决方案

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.

Simon

这篇关于精确替换图像中的一个像素,然后通过Swift将其放置在另一图像中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆