我如何读取Python中给定像素的RGB值? [英] How can I read the RGB value of a given pixel in Python?
问题描述
如果我用 open(image.jpg)
打开一个图像,我如何获得一个像素的RGB值,假设我有像素的坐标?
然后,我怎么能做到这一点呢?从一张空白图像开始,写一个具有某个RGB值的像素?
如果我不需要下载任何额外的库,我宁愿选择它。
最好使用 Python图像库来做到这一点,我恐怕是一个单独的下载。
最简单的方法来做你想要的是通过 Image对象的load()方法,它返回一个像素访问对象,你可以像数组一样操作它:
from PIL import Image
im = Image.open('dead_parrot.jpg')#可以是许多不同的格式。
pix = im.load()
print im.size#获取图像的宽度和高度以迭代
print pix [x,y]#获取a的RGBA值图像的像素
pix [x,y] = value#设置图像(元组)的RGBA值
im.save('alive_parrot.png')#将修改的像素保存为.png
或者,查看 ImageDraw ,它为创建图像提供了更加丰富的API。
If I open an image with open("image.jpg")
, how can I get the RGB values of a pixel assuming I have the coordinates of the pixel?
Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value?
I would prefer if I didn't have to download any additional libraries.
It's probably best to use the Python Image Library to do this which I'm afraid is a separate download.
The easiest way to do what you want is via the load() method on the Image object which returns a pixel access object which you can manipulate like an array:
from PIL import Image
im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size # Get the width and hight of the image for iterating over
print pix[x,y] # Get the RGBA Value of the a pixel of an image
pix[x,y] = value # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png') # Save the modified pixels as .png
Alternatively, look at ImageDraw which gives a much richer API for creating images.
这篇关于我如何读取Python中给定像素的RGB值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!