python - 获取图像像素数据而不保存
问题描述
有没有办法从图像中获取给定坐标处的 RGB 值而无需将其保存到磁盘?那么是否可以只使用 Python 库输入图像的 URL 并读取它们的 RGB 数据(或者保存然后删除它们是最好的方法)?
解决方案
根据您要完成的任务的性质,无需将图像保存到文件中。你还没有说你想使用哪个成像库。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]
推荐阅读
- javascript - 未从角度调用 Web API
- c++ - BMP 的问题
- javascript - Vue路由器加载子路由失败
- bi-publisher - 将参数插入模板循环
- python - 为什么 head() 返回 IndexError:太多级别:索引只有 1 级,而不是 dask 数据帧中的 2?
- ruby - 剥离字符串以构建新的 S3 路径
- reactjs - React:提供上传的默认文件
- java - 如何在现有的 json 节点中写入而不丢失 java 中的数据?
- javascript - 我想在 Javascript 中使用 fetch 函数外部的变量
- notion-api - 是否可以在概念内创建一个按钮或链接来调用概念 API?