如何将RGBA字节串转换为灰度图像?

问题描述 投票:1回答:2

我在RGBA中有一个图像的字节数组(从django中的请求接收),我想要灰度。我该怎么做?

基本上,我有一个字节串(例如,b'\x00\x00\x00....\x00',图像的RGBA值的单字节字符串),我想将其转换为灰度numpy数组,如:

[[0,  0,...,0],
 [255,0,...,0],
 [...],
 [...]]

对于360000像素的图像,字节数组的长度是300x300

python opencv
2个回答
0
投票

您可以将您的bytestring转换为np.array,然后将其转换为灰度或执行您可能需要的任何操作。

import cv2
import numpy as np

# this is to simulate your bytestring
x = b'\x00'*300*300*4

# convert to np.array()
img = np.frombuffer(x, dtype=np.uint8).reshape((300, 300, 4))

print(img.shape)
# (300, 300, 4)

# process the image, e.g.,
img_gray = cv2.cvtColor(img, cv2.COLOR_RGBA2GRAY)

print(img_gray.shape)
# (300, 300)

0
投票

使用opencv,您可以使用该行gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)将图像转换为灰度

我希望它会对你有所帮助!

阿德里安

© www.soinside.com 2019 - 2024. All rights reserved.