简体   繁体   English

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

[英]python , opencv, image array to binary

I have a large image , using cv2 module in python and some coordinates i cropped the image: 我有一个大图像,使用python中的cv2模块和一些坐标我裁剪图像:

  img = cv.imread(image_path)
  crop_img = img[y1:y2,x1:x2]
  cv.imwrite(cropPath, crop_img)

now the crop_img is a numpy.ndarray type. 现在crop_img是一个numpy.ndarray类型。 then I save this image to disk and read its contents in a binary format using an open() function 然后我将此图像保存到磁盘并使用open()函数以二进制格式读取其内容

  with open(cropPath, 'rb') as image_file:
    content = image_file.read()

and I get the binary representation. 我得到二进制表示。 Is there any way to do the above operations without saving the image to disk. 有没有办法在不将图像保存到磁盘的情况下执行上述操作。 Not saving to disk will save a lot of time, I am not able to find any method to do this. 不保存到磁盘将节省大量时间,我无法找到任何方法来执行此操作。 if anyone could point in the right direction, that would be helpful. 如果有人能指出正确的方向,那将会有所帮助。

found the answer on this thread: Python OpenCV convert image to byte string? 在这个帖子上找到答案: Python OpenCV将图像转换为字节串?

converting a image represented through a numpy array into string can be done by using imencode and tostring functions in cv2 将通过numpy数组表示的图像转换为字符串可以通过使用cv2中的imencode和tostring函数来完成

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

If you use cv2.imwrite() , then you will get an image in image format,such as png, jpg, bmp and so on. 如果您使用cv2.imwrite() ,那么您将获得图像格式的图像,例如png, jpg, bmp等。 Now if you open(xxx,"rb") as a normal binary file, it will go wrong, because it is AN IMAGE in IMAGE FILE FORMAT . 现在如果你open(xxx,"rb")作为普通的二进制文件,它会出错,因为它是AN IMAGE in IMAGE FILE FORMAT

The simplest way is use np.save() to save the np.ndarray to the disk ( serialize ) in .npy format. 最简单的方法是使用np.save()以.npy格式将np.ndarray保存到磁盘( serialize )。 The use np.load() to load from disk ( deserialize ). 使用np.load()从磁盘加载( deserialize )。

An alternative is pickle.dump()/pickle.load() . 另一种方法是pickle.dump()/pickle.load()

Here is an example: 这是一个例子:

#!/usr/bin/python3
# 2017.10.04 21:39:35 CST

import pickle 
imgname = "Pictures/cat.jpg"

## use cv2.imread()/cv2.imwrite() 
img = cv2.imread(imgname)

## use np.save() / np.load()
np.save(open("another_cat1.npy","wb+"), img)
cat1 = np.load(open("another_cat1.npy","rb"))

## use pickle.dump() / pickle.load()
pickle.dump(img, open("another_cat2.npy","wb+"))
cat2 = pickle.load(open("another_cat2.npy", "rb"))

cv2.imshow("img", img);
cv2.imshow("cat1", cat1);
cv2.imshow("cat2", cat2);
cv2.waitKey();cv2.destroyAllWindows()

The result: 结果:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM