Python3 OpenCV imshow() 字节串

Python3 OpenCV imshow() bytes string

我的相机有一个字节串,我想用 OpenCV 显示帧而不保存它(节省时间)。我检查了这个问题:Python OpenCV load image from byte string 但我收到错误 failed to import cv from cv2

打印(帧):b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\...

我的代码(在一个循环中):

frame = # need to convert bytestring for imshow()
cv2.imshow('image', frame)
cv2.waitKey(1)

此外,如果我只是将它保存为一个文件,然后用 cv2.imread(..) 加载它,代码就可以工作,但最好是跳过文件保存和加载。

所以这不再有效,因为 cv 已从 OpenCV3 中删除。

nparr = np.fromstring(frame, np.uint8)
img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

img_ipl = cv.CreateImageHeader((img_np.shape[1], img_np.shape[0]), cv.IPL_DEPTH_8U, 3)
cv.SetData(img_ipl, img_np.tostring(), img_np.dtype.itemsize * 3 * img_np.shape[1])

cv2.imshow('image', img_ipl)
cv2.waitKey(1)

如何在不创建临时文件的情况下传递字节串?

import numpy as np
import cv2

# Load image as string from file/database
fd = open('foo.jpg')
img_str = fd.read()
fd.close()

#Convert to images
image = np.fromstring(im_str, np.uint8).reshape( h, w, nb_planes )
cv2.imshow('Output', image)

所以,找到了解决方案:

# converting bytestring frame into imshow argument
nparr = np.fromstring(frame, np.uint8)
frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

cv2.imshow('image', frame)
cv2.waitKey(1)