准确替换图像中的一个像素并通过 Swift 将其放入另一张图像中 [英] Replace exactly one pixel in an image and put it in another image via Swift
问题描述
简单地说,如果我有一个图像 I
和另一个图像 J
,我想替换 I(t,s) 位置的 RGB 值)
并将该像素分配给 J(t,s)
.我如何在 Core Image 或使用自定义内核中做到这一点?
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?
考虑到 Core Image 的工作方式,这似乎不是一件容易的事.但是,我想知道是否有一种方法可以提取 (t,s)
处的像素值,创建一个与 J<一样大的图像
K
/code> 只用那个像素,然后只在那个点用 K
覆盖 J
.只是一个想法,希望有更好的方法.
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))
如果我们要设置像素为500,100为蓝色:
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)
以下将创建一个名为 final
的 CIImage
,在红海中带有一个蓝色像素:
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.
西蒙
这篇关于准确替换图像中的一个像素并通过 Swift 将其放入另一张图像中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!