如何在Python中读取给定像素的RGB值? [英] How to read the RGB value of a given pixel in Python?
问题描述
如果使用open("image.jpg")
打开图像,假设我具有像素的坐标,如何获得像素的RGB值?
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?
然后,我该怎么做呢?从空白图形开始,写入"具有一定RGB值的像素吗?
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.
推荐答案
最好使用 Python图片库要执行此操作,恐怕是单独下载.
It's probably best to use the Python Image Library to do this which I'm afraid is a separate download.
最简单的方法是通过Image对象上的 load()方法会返回一个像素访问对象,您可以像数组一样对其进行操作:
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
或者,查看 ImageDraw ,它提供了更丰富的API,可用于创建图像.
Alternatively, look at ImageDraw which gives a much richer API for creating images.
这篇关于如何在Python中读取给定像素的RGB值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!