如果我使用
然后,我该如何反向操作?从一个空白的图形开始,'写入'具有特定RGB值的像素?
我希望不必下载任何其他库。
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。
from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())
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 个三元组颜色#fff
吗? - d9nglepixel_values = numpy.array(pixel_values).reshape((height, width, channels))
。 - ChifrijoPyPNG - 轻量级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是一个更全面的图像库,但相对来说更加笨重。
正如Dave Webb所说:
以下是我工作的代码片段,用于打印图像中的像素颜色:
import os, sys import Image im = Image.open("image.jpg") x = 3 y = 4 pix = im.load() print pix[x,y]
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: 无法识别图像文件 'test_images/test_UAV.tif'```
- just_learningphoto = 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
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
*注意:我不是这段代码的原作者;它没有解释就被留下了。由于它很容易解释,我只是提供了解释,以防后面有人不理解。
图像处理是一个复杂的主题,最好使用库进行处理。我可以推荐gdmodule,它可以在Python中轻松访问许多不同的图像格式。
在wiki.wxpython.org上有一篇非常好的文章,标题为“使用图像”。该文章提到了使用wxWidgets(wxImage)、PIL或PythonMagick的可能性。就我个人而言,我已经使用过PIL和wxWidgets,它们都使图像处理变得相当简单。
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
#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(" ")))
PhotoImage(file="image.png")
加载现有图像。 - mathieures
pip
安装了 PIL,这件事情相当简单。 - michaelliueasy_install --find-links http://www.pythonware.com/products/pil/ Imaging
- Mazyodpip install pillow
将会成功并且相当快地安装PIL(如果不在虚拟环境中,可能需要使用sudo
)。 - Christopher Shroba