I am reading binary data [sqlite3.Binary] from sqlite BLOB in which a JPEG image is saved. The image is written to the database using
img = cv2.imread("images\\image.jpg")
c.execute('INSERT INTO pictures (serial_no, image, height, width) VALUES(?, ?, ?, ?)',
(serial_no, sqlite3.Binary(img), img.shape[0], img.shape[1]))
Trying to restore an image as follows:
conn = sqlite3.connect(dbname)
c = conn.cursor()
c.execute('SELECT image, height, width FROM pictures WHERE serial_no=?', (serial_no, ))
raw, height, width = c.fetchone()
raw_str = StringIO.StringIO(raw)
arr = np.asarray(bytearray(raw_str.read()), dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
The last step always fails, and imdecode returns None.
What works, however, is numpy.resape:
image = arr.copy().reshape((height, width, 3))
I tested both OpenCV 3.0.0 and OpenCV 2.4.11, where both give the same unsatisfactory result.
What am I missing?