如何在 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屋!