从 CV2 从在线 MJPG 流光中捕获的图像,我想用 Pillow 计算它的颜色。
我尝试了什么:
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'
更新的答案
这里不需要使用 PIL,您已经有了一个 Numpy 数组(OpenCV 用于图像)并且您正在使用
np.unique()
来计算颜色,这也是基于 Numpy 数组的。
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)
colours, counts = np.unique(img_cv2.reshape(-1,3), axis=0, return_counts=1)
print(len(counts))
此外,如果您只想要颜色的数量,则没有真正需要从 BGR 转换为 RGB,因为两种颜色空间中的颜色数量都是相同的。
原答案
您已有一个
PIL Image
,无需再打开:
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)
colours, counts = np.unique(img_pil.reshape(-1,3), axis=0, return_counts=1)
print(len(counts))
此外,如果您只想要颜色的数量,则没有真正需要从 BGR 转换为 RGB,因为两种颜色空间中的颜色数量都是相同的。