如果我打开图像open("image.jpg")
,我怎么能得到一个像素的RGB值,假设我有像素的坐标?
然后,我该怎么做呢?从空白图形开始,"写入"具有特定RGB值的像素?
如果我不必下载任何其他库,我更愿意.
最好使用Python Image Library来执行此操作,我担心这是一个单独的下载.
执行所需操作的最简单方法是通过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.
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模块,包括测试和注释.
PIL是一个更全面的成像库,但它也显着更重.
使用Pillow(适用于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]
一个完整,简单易用的解决方案
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