Rmagickeach_pixel,它是如何工作的?

发布于 2025-01-01 00:32:00 字数 340 浏览 3 评论 0原文

我需要在 rmagick 中操作图像的每个像素。我正在 IRB(交互式红宝石)中执行此操作,这就是我所拥有的:

require 'Rmagick'
include Magick
f = Image.new(100,100)
f.display #so far so good. A 100x100 white image is displayed

f.each_pixel {|pixel, c, r| pixel.red = 0}
f.display #the image is still white. It should really be a shade of blue.

我做错了什么?

I need to manipulate each pixel of an image in rmagick. I am doing this in IRB(interactive ruby) This is what I have:

require 'Rmagick'
include Magick
f = Image.new(100,100)
f.display #so far so good. A 100x100 white image is displayed

f.each_pixel {|pixel, c, r| pixel.red = 0}
f.display #the image is still white. It should really be a shade of blue.

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

拥抱没勇气 2025-01-08 00:32:00

问题是,从each_pixel 返回的数组是一个新的数据集。数据需要存储回图像。

使用 get_pixels 和 store_pixels 代替:

img = Magick::ImageList.new('img.jpg').first
pixels = img.get_pixels(0,0,img.columns,img.rows)

for pixel in pixels
    avg = (pixel.red + pixel.green + pixel.blue) / 3
    pixel.red = avg
    pixel.blue = avg
    pixel.green = avg
end

img.store_pixels(0,0, img.columns, img.rows, pixels)
img.display

The thing is, the array you get back from each_pixel is a new dataset. The data needs to be stored back to the image.

Use get_pixels and store_pixels instead:

img = Magick::ImageList.new('img.jpg').first
pixels = img.get_pixels(0,0,img.columns,img.rows)

for pixel in pixels
    avg = (pixel.red + pixel.green + pixel.blue) / 3
    pixel.red = avg
    pixel.blue = avg
    pixel.green = avg
end

img.store_pixels(0,0, img.columns, img.rows, pixels)
img.display
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文