簡體   English   中英

Python OpenCV 將圖像轉換為字節字符串?

[英]Python OpenCV convert image to byte string?

我正在使用 PyOpenCV。 如何將 cv2 圖像(numpy)轉換為二進制字符串,以便在沒有臨時文件和imwrite情況下寫入 MySQL 數據庫?

我用谷歌搜索,但什么也沒找到……

我正在嘗試imencode ,但它不起作用。

capture = cv2.VideoCapture(url.path)
capture.set(cv2.cv.CV_CAP_PROP_POS_MSEC, float(url.query))
self.wfile.write(cv2.imencode('png', capture.read()))

錯誤:

  File "server.py", line 16, in do_GET
  self.wfile.write(cv2.imencode('png', capture.read()))
  TypeError: img is not a numerical tuple

幫助某人!

如果您有圖像img (這是一個 numpy 數組),您可以使用以下方法將其轉換為字符串:

>>> img_str = cv2.imencode('.jpg', img)[1].tostring()
>>> type(img_str)
 'str'

現在您可以輕松地將圖像存儲在數據庫中,然后使用以下命令恢復它:

>>> nparr = np.fromstring(STRING_FROM_DATABASE, np.uint8)
>>> img = cv2.imdecode(nparr, cv2.CV_LOAD_IMAGE_COLOR)

您需要將STRING_FROM_DATABASE替換為包含對包含圖像的數據庫的查詢結果的變量。

它在 2020 年使用 numpy==1.19.4 和 opencv==4.4.0:

import cv2

cam = cv2.VideoCapture(0)

# get image from web camera
ret, frame = cam.read()

# convert to jpeg and save in variable
image_bytes = cv2.imencode('.jpg', frame)[1].tobytes()

capture.read() 返回一個元組,(err,img)。

嘗試拆分它:

_,img = capture.read()
self.wfile.write(cv2.imencode('png', img))
im = cv2.imread('/tmp/sourcepic.jpeg')
res, im_png = cv2.imencode('.png', im)
with open('/tmp/pic.png', 'wb') as f:
    f.write(im_png.tobytes())

我在 python cgi 中使用 opencv 的代碼:

    im_data = form['image'].file.read()
    im = cv2.imdecode( np.asarray(bytearray(im_data), dtype=np.uint8), 1 )
    ret, im_thresh = cv2.threshold( im, 128, 255, cv2.THRESH_BINARY )
    self.send_response(200)
    self.send_header("Content-type", "image/jpg")
    self.end_headers()      
    ret, buf = cv2.imencode( '.jpg', im_thresh )
    self.wfile.write( np.array(buf).tostring() )

下面是一個例子:

def image_to_bts(frame):
    '''
    :param frame: WxHx3 ndarray
    '''
    _, bts = cv2.imencode('.webp', frame)
    bts = bts.tostring()
    return bts

def bts_to_img(bts):
    '''
    :param bts: results from image_to_bts
    '''
    buff = np.fromstring(bts, np.uint8)
    buff = buff.reshape(1, -1)
    img = cv2.imdecode(buff, cv2.IMREAD_COLOR)
    return img

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM