1

I've got a bytestring from my camera and I'd like to show the frame with OpenCV WITHOUT saving it (saving time). I've checked this question: Python OpenCV load image from byte string but I get an error failed to import cv from cv2.

print(frame): b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\...

My code (in a loop ofc):

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

Also, the code worked if I just saved it as a file, then loaded it with cv2.imread(..), but the best would be to skip filesave and load.

So this doesn't work anymore, as cv was removed from 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)

How can then pass the bytestring without creating a temporary file?

Community
  • 1
  • 1

2 Answers2

0
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)
Adnan Sabbir
  • 181
  • 1
  • 13
  • `NameError: name 'cv' is not defined`. If I use `from cv2 import cv` from the question mentioned: `ImportError: cannot import name 'cv'` –  Apr 14 '19 at 22:54
  • Have you installed the CV2 library? – Adnan Sabbir Apr 14 '19 at 22:56
  • Running cv2.__version__ shows 4.1.0, so I guess? I'm running this on Python3. –  Apr 14 '19 at 22:58
  • Unfortunately, cv is removed from CV2 in OpenCV3. So you can use it. I just got to know from here - http://answers.opencv.org/question/69126/python-import-cv-error-on-opencv-300-no-error-for-import-cv2/ – Adnan Sabbir Apr 14 '19 at 23:03
0

So, found a solution:

# 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)