首页 > 解决方案 > 获取图像像素数据而不保存

问题描述

有没有办法从图像中获取给定坐标处的 RGB 值而无需将其保存到磁盘?那么是否可以只使用 Python 库输入图像的 URL 并读取它们的 RGB 数据(或者保存然后删除它们是最好的方法)?

标签: pythonimageimage-processingdownload

解决方案


根据您要完成的任务的性质,无需将图像保存到文件中。你还没有说你想使用哪个成像库。PIL(现在的枕头)是一个非常受欢迎的选择。但还有其他人。

许多人喜欢使用Requests来管理 URL 下载。但它是一个额外的模块来安装。你也可以试试 urllib.request.urlopen,它是标准库的一部分。

这是一小段代码,它将使用 PIL(枕头)加上 urllib 或 Python3 中的请求:

编辑:原始答案没有演示如何访问像素数据。代码已更新。

from PIL import Image
from io import BytesIO

# BBC Test Card F image from 1967
url = 'https://upload.wikimedia.org/wikipedia/en/5/52/Testcard_F.jpg'

# load the image with urllib + BytesIO
import urllib.request

response = urllib.request.urlopen(url)
img = Image.open(BytesIO(response.read()))

# load the image with requests
import requests

response = requests.get(url)
img = Image.open(BytesIO(response.content))

# it is very likely every image you come across will already be RGB
# so next line is usually not needed
#img = img.convert('RGB')

r, g, b = img.getpixel((1, 1))

print(r, g, b)

# if you already use NumPy, you can convert the image to a NumPy array
# and access pixels that way

import numpy as np
npimg = np.array(img) # 3 dim array first to dims are pixel x,y
                      # last dim is color
r, g, b = npimg[1,1,:]
print(r, g, b)        # r = npimg[1,1,0], g = npimg[1,1,1], b = npimg[1,1,2]

推荐阅读