从CV2从在线MJPG流媒体捕获的图像中,我想通过枕头来计算其颜色。
我尝试的是:
import cv2
from PIL import Image
url = "http://link-to-the-online-MJPG-streamer/mjpg/video.mjpg"
cap = cv2.VideoCapture(url)
ret, original_image = cap.read()
img_cv2 = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img_cv2)
im = Image.open(img_cv2).convert('RGB')
na = np.array(im)
colours, counts = np.unique(na.reshape(-1,3), axis=0, return_counts=1)
print(len(counts))
但它显示了一个错误。
将CV2捕获的图像转换为Pillow格式的正确方法是什么?
谢谢大家。
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages \PIL\Image.py", line 3231, in open
fp.seek(0)
AttributeError: 'numpy.ndarray' object has no attribute 'seek'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:\Python\Script.py", line 17, in <module>
im = Image.open(img_cv2).convert('RGB')
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python38-32\lib\site-packages \PIL\Image.py", line 3233, in open
fp = io.BytesIO(fp.read())
AttributeError: 'numpy.ndarray' object has no attribute 'read'
1条答案
按热度按时间23c0lvtd1#
更新答案
这里不需要使用PIL,你已经有了一个Numpy数组(这是OpenCV用于图像的),你正在使用
np.unique()
来计算颜色,这也是基于Numpy数组的。此外,如果你只是想要颜色的数量,没有真实的的需要从BGR转换到RGB,因为颜色的数量在两个颜色空间中是相同的。
此外,请注意,使用
np.dot()
可以更快地完成这一任务,如this答案末尾所示。原始答案
您已经有一个
PIL Image
,无需再打开另一个:此外,如果你只是想要颜色的数量,没有真实的的需要从BGR转换到RGB,因为颜色的数量在两个颜色空间中是相同的。