如果我用 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

wiki.wxpython.org上有一篇非常好的文章,名为使用图片 。文章提到了使用wxWidgets(wxImage),PIL或PythonMagick的可能性。就个人而言,我已经使用了PIL和wxWidgets,这两种方法都使图像处理相当容易。

您可以使用 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

我希望有所帮助。最后一句话:屏幕在屏幕截图的生命周期内被锁定。

图像处理是一个复杂的主题,如果使用库,最好。我可以推荐 gdmodule ,它可以从Python中轻松访问许多不同的图像格式。

使用命令“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]

您可以使用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(" ")))
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

img=mpimg.imread('Cricket_ACT_official_logo.png')
imgplot = plt.imshow(img)
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

如果您希望以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)

这可能适合你。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top