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

2025-02-10 08:57:00
admin
原创
57
摘要:问题描述:如果我用 打开一张图片open("image.jpg"),假设我有该像素的坐标,我该如何获取该像素的 RGB 值?那么,我该如何做相反的事情呢?从空白图形开始,“写入”具有特定 RGB 值的像素?如果我不需要下载任何额外的库那就更好了。解决方案 1:最好使用Python 图像库来...

问题描述:

如果我用 打开一张图片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)

这可能对你有用。

相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用