Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python , opencv, image array to binary

I have a large image , using cv2 module in python and some coordinates i cropped the image:

  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. then I save this image to disk and read its contents in a binary format using an open() function

  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.

like image 450
Tarun Reddy Avatar asked Oct 04 '17 11:10

Tarun Reddy


2 Answers

found the answer on this thread: Python OpenCV convert image to byte string?

converting a image represented through a numpy array into string can be done by using imencode and tostring functions in cv2

>>> img_str = cv.imencode('.jpg', img)[1].tostring()
>>> type(img_str)
 'str'
like image 140
Tarun Reddy Avatar answered Sep 17 '22 07:09

Tarun Reddy


If you use cv2.imwrite(), then you will get an image in image format,such as png, jpg, bmp and so on. Now if you open(xxx,"rb") as a normal binary file, it will go wrong, because it is 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. The use np.load() to load from disk (deserialize).

An alternative is 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:

enter image description here

like image 30
Kinght 金 Avatar answered Sep 21 '22 07:09

Kinght 金