1

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()
Eli Halych
  • 545
  • 7
  • 25
sunknudsen
  • 6,356
  • 3
  • 39
  • 76
  • 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. – Mark Setchell Oct 11 '20 at 13:17
  • @MarkSetchell Interesting... thanks for helping out. Would you happen to know how to read `qr.png(buffer)` using `cv2`? – sunknudsen Oct 11 '20 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` – Mark Setchell Oct 11 '20 at 14:48

1 Answers1

1

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()
sunknudsen
  • 6,356
  • 3
  • 39
  • 76
  • Well done! Thank you for sharing back with the SO community. – Mark Setchell Oct 11 '20 at 15:04
  • @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? – sunknudsen Oct 13 '20 at 11:44
  • @MarkSetchell Fixed the issue thanks to https://stackoverflow.com/a/47389660/4579271 and updated my answer. – sunknudsen Oct 13 '20 at 12:36