2

This is what I have so far... can't figure out how to read image from buffer vs file?

import pyqrcode
import io
from cv2 import cv2

qr = pyqrcode.create("Hello")
buffer = io.BytesIO()
qr.svg(buffer)
# image = cv2.imread(path) // How to read image from buffer instead?
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
3
  • I don't believe OpenCV can read vector graphics such as SVG, I think it only reads bitmapped graphics - I may be wrong. I suspect you'll either have to get pyqrcode to output a PNG (of which it is capable), or use pyvips or wand to read the SVG. If anyone knows better I am always happy to be corrected. Commented Oct 11, 2020 at 13:17
  • @MarkSetchell Interesting... thanks for helping out. Would you happen to know how to read qr.png(buffer) using cv2? Commented Oct 11, 2020 at 14:37
  • 1
    You'll need something like cv2.imdecode(np.array(buffer.getcontents()), cv2.IMREAD_COLOR)) I'm not at a computer to test. You basically need to run cv2.imdecode() on something that looks like bytes or a Numpy array and starts with a PNG signature \x89PNG Commented Oct 11, 2020 at 14:48

1 Answer 1

2

The following worked. Thanks Mark!

import pyqrcode
import io
import numpy as np
from cv2 import cv2

buffer = io.BytesIO()
qr = pyqrcode.create("Hello")
qr.png(buffer)
buffer.seek(0)
array = np.asarray(bytearray(buffer.read()), dtype=np.uint8)
image = cv2.imdecode(array, cv2.IMREAD_COLOR)
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up to request clarification or add additional context in comments.

3 Comments

Well done! Thank you for sharing back with the SO community.
@MarkSetchell Hey Mark, depending on what I feed to np.frombuffer, I am getting ValueError: buffer size must be a multiple of element size. Would you happen to know what is going on?
@MarkSetchell Fixed the issue thanks to stackoverflow.com/a/47389660/4579271 and updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.