我如何读取Python中给定像素的RGB值?

如果我用open("image.jpg")打开图像,如果我有像素的坐标,如何获得像素的RGB值?

那我怎么能做到这一点呢? 从一个空白的graphics开始,写一个具有一定RGB值的像素?

如果我不必下载任何额外的库,情况会好得多。

这可能是最好的使用Python图像库来做到这一点,恐怕是一个单独的下载。

最简单的方法是通过Image对象上的load()方法来返回一个像素访问对象,您可以像数组一样操作:

 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来创build图像。

PyPNG – 轻量级的PNG解码器/编码器

虽然问题提示JPG,但我希望我的回答对一些人有用。

以下是如何使用PyPNG模块读取和写入PNG像素:

 import png, array point = (2, 10) # coordinates of pixel to be painted red reader = png.Reader(filename='image.png') w, h, pixels, metadata = reader.read_flat() pixel_byte_width = 4 if metadata['alpha'] else 3 pixel_position = point[0] + point[1] * w new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0) pixels[ pixel_position * pixel_byte_width : (pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value) output = open('image-with-red-dot.png', 'wb') writer = png.Writer(w, h, **metadata) writer.write_array(output, pixels) output.close() 

PyPNG是一个长度不超过4000行的纯Python模块,包括testing和注释。

PIL是一个更全面的图像库,但它也显着更重。

使用枕头 (与Python 3.X以及Python 2.7+一起使用),您可以执行以下操作:

 from PIL import Image im = Image.open('image.jpg', 'r') width, height = im.size pixel_values = list(im.getdata()) 

现在你有所有的像素值。 如果是RGB或其他模式可以通过im.mode读取。 那么你可以通过以下方式获得像素(x, y)

 pixel_values[width*y+x] 

或者,您可以使用Numpy并重新整理数组:

 >>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3)) >>> x, y = 0, 1 >>> pixel_values[x][y] [ 18 18 12] 

一个完整的,简单易用的解决scheme是

 def get_image(image_path): """Get a numpy array of an image so that one can access values[x][y].""" image = Image.open(image_path, 'r') width, height = image.size pixel_values = list(image.getdata()) if image.mode == 'RGB': channels = 3 elif image.mode == 'L': channels = 1 else: print("Unknown mode: %s" % image.mode) return None pixel_values = numpy.array(pixel_values).reshape((width, height, channels)) return pixel_values 

正如Dave Webb所说。

这里是我的工作代码片段打印图像的像素颜色:

 import os, sys import Image im = Image.open("image.jpg") x = 3 y = 4 pix = im.load() print pix[x,y] 
 photo = Image.open('IN.jpg') #your image photo = photo.convert('RGB') width = photo.size[0] #define W and H height = photo.size[1] for y in range(0, height): #each pixel has coordinates row = "" for x in range(0, width): RGB = photo.getpixel((x,y)) R,G,B = RGB #now you can use the RGB value 

wiki.wxpython.org上有一篇非常不错的文章,名为Working With Images 。 文章提到了使用wxWidgets(wxImage),PIL或PythonMagick的可能性。 就我个人而言,我使用PIL和wxWidgets,都使image processing相当容易。

你可以使用pygame的surfarray模块。 这个模块有一个叫做pixels3d(surface)的3d像素数组返回方法。 我已经在下面显示了用法:

 from pygame import surfarray, image, display import pygame import numpy #important to import pygame.init() image = image.load("myimagefile.jpg") #surface to render resolution = (image.get_width(),image.get_height()) screen = display.set_mode(resolution) #create space for display screen.blit(image, (0,0)) #superpose image on screen display.flip() surfarray.use_arraytype("numpy") #important! screenpix = surfarray.pixels3d(image) #pixels in 3d array: #[x][y][rgb] for y in range(resolution[1]): for x in range(resolution[0]): for color in range(3): screenpix[x][y][color] += 128 #reverting colors screen.blit(surfarray.make_surface(screenpix), (0,0)) #superpose on screen display.flip() #update display while 1: print finished 

我希望有帮助。 最后一句话:屏幕locking终身的screenpix。

使用命令“sudo apt-get install python-imaging”安装PIL并运行以下程序。 它将打印图像的RGB值。 如果图像很大,则使用“>”将输出redirect到文件,然后打开文件以查看RGB值

 import PIL import Image FILENAME='fn.gif' #image can be in gif jpeg or png format im=Image.open(FILENAME).convert('RGB') pix=im.load() w=im.size[0] h=im.size[1] for i in range(w): for j in range(h): print pix[i,j] 

你可以使用Tkinter模块,它是Tk GUI工具包的标准Python接口,你不需要额外的下载。 请参阅https://docs.python.org/2/library/tkinter.html

(对于Python 3,Tkinter被重命名为tkinter)

这里是如何设置RGB值:

 #from http://tkinter.unpythonic.net/wiki/PhotoImage from Tkinter import * root = Tk() def pixel(image, pos, color): """Place pixel at pos=(x,y) on image, with color=(r,g,b).""" r,g,b = color x,y = pos image.put("#%02x%02x%02x" % (r,g,b), (y, x)) photo = PhotoImage(width=32, height=32) pixel(photo, (16,16), (255,0,0)) # One lone pixel in the middle... label = Label(root, image=photo) label.grid() root.mainloop() 

并获得RGB:

 #from http://www.kosbie.net/cmu/spring-14/15-112/handouts/steganographyEncoder.py def getRGB(image, x, y): value = image.get(x, y) return tuple(map(int, value.split(" "))) 

image processing是一个复杂的主题,最好使用库。 我可以推荐gdmodule ,它可以很容易地从Python中访问许多不同的图像格式。

 import matplotlib.pyplot as plt import matplotlib.image as mpimg img=mpimg.imread('Cricket_ACT_official_logo.png') imgplot = plt.imshow(img)