如何在 Python 中读取给定像素的 RGB 值?
- 2025-02-10 08:57:00
- admin 原创
- 57
问题描述:
如果我用 打开一张图片open("image.jpg")
,假设我有该像素的坐标,我该如何获取该像素的 RGB 值?
那么,我该如何做相反的事情呢?从空白图形开始,“写入”具有特定 RGB 值的像素?
如果我不需要下载任何额外的库那就更好了。
解决方案 1:
最好使用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。
解决方案 2:
使用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]
一个完整且易于使用的解决方案是
# Third party modules
import numpy
from PIL import Image
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
image = get_image("gradient.png")
print(image[0])
print(image.shape)
冒烟测试代码
您可能不确定宽度/高度/通道的顺序。为此,我创建了这个渐变:
该图像的宽度为 100px,高度为 26px。它的颜色渐变从#ffaa00
(黄色)到#ffffff
(白色)。输出为:
[[255 172 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 172 5]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 4]
[255 172 5]
[255 171 5]
[255 171 5]
[255 172 5]]
(100, 26, 3)
注意事项:
形状为(宽度、高度、通道)
因此第一行
image[0]
有 26 个相同颜色的三元组
解决方案 3:
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 是一个纯 Python 模块,长度不到 4000 行,包括测试和注释。
PIL是一个更全面的图像库,但它的重量也明显较大。
解决方案 4:
正如戴夫·韦伯所说:
下面是我从图像中打印像素颜色的工作代码片段:
import os, sys import Image im = Image.open("image.jpg") x = 3 y = 4 pix = im.load() print pix[x,y]
解决方案 5:
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
解决方案 6:
使用名为 Pillow 的库,您可以将其变成一个函数,以便以后在程序中轻松使用,并且如果您必须多次使用它。该函数只需输入图像的路径和要“抓取”的像素的坐标即可。它打开图像,将其转换为 RGB 颜色空间,并返回所请求像素的 R、G 和 B。
from PIL import Image
def rgb_of_pixel(img_path, x, y):
im = Image.open(img_path).convert('RGB')
r, g, b = im.getpixel((x, y))
a = (r, g, b)
return a
*注:我不是这段代码的原作者;它没有解释。由于解释起来相当容易,我只是提供上述解释,以防有人不明白。
解决方案 7:
您可以使用 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(" ")))
解决方案 8:
图像处理是一个复杂的主题,最好使用库。我推荐gdmodule,它可以轻松从 Python 中访问许多不同的图像格式。
解决方案 9:
wiki.wxpython.org 上有一篇非常好的文章,题为“处理图像”。文章提到了使用 wxWidgets (wxImage)、PIL 或 PythonMagick 的可能性。就我个人而言,我使用过 PIL 和 wxWidgets,它们都使图像处理相当容易。
解决方案 10:
您可以使用pygame的 surfarray 模块。此模块有一个 3d 像素数组返回方法,称为 pixels3d(surface)。我已在下面展示了用法:
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
希望对您有所帮助。最后一句话:screenpix 的整个生命周期内屏幕均处于锁定状态。
解决方案 11:
使用命令“sudo apt-get install python-imaging”安装 PIL 并运行以下程序。它将打印图像的 RGB 值。如果图像很大,请使用“>”将输出重定向到文件,稍后打开文件以查看 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]
解决方案 12:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('Cricket_ACT_official_logo.png')
imgplot = plt.imshow(img)
解决方案 13:
如果您希望以 RGB 颜色代码的形式获得三位数字,则以下代码就可以实现。
i = Image.open(path)
pixels = i.load() # this is not a list, nor is it list()'able
width, height = i.size
all_pixels = []
for x in range(width):
for y in range(height):
cpixel = pixels[x, y]
all_pixels.append(cpixel)
这可能对你有用。