python,opencv,图像数组转二进制

Tar*_*ddy 6 python opencv numpy image

我有一个大图像,在 python 中使用 cv2 模块和一些坐标我裁剪了图像:

  img = cv.imread(image_path)
  crop_img = img[y1:y2,x1:x2]
  cv.imwrite(cropPath, crop_img)
Run Code Online (Sandbox Code Playgroud)

现在crop_img 是一个numpy.ndarray 类型。然后我将此图像保存到磁盘并使用 open() 函数以二进制格式读取其内容

  with open(cropPath, 'rb') as image_file:
    content = image_file.read()
Run Code Online (Sandbox Code Playgroud)

我得到了二进制表示。有没有办法在不将图像保存到磁盘的情况下进行上述操作。不保存到磁盘会节省很多时间,我找不到任何方法来做到这一点。如果有人能指出正确的方向,那会很有帮助。

Tar*_*ddy 5

在此线程上找到了答案: Python OpenCV将图像转换为字节字符串?

将通过 numpy 数组表示的图像转换为字符串可以通过使用 cv2 中的 imencode 和 tostring 函数来完成

>>> img_str = cv.imencode('.jpg', img)[1].tostring()
>>> type(img_str)
 'str'
Run Code Online (Sandbox Code Playgroud)