Python + OpenCV to convert image to binary format

Time:2021-4-17

In the process of learning tensorflow, there is a problem. In the process of training, tensorflow reads the binary image database file, not the image file, so it is difficult to read the binary image database file

Before training and testing, we need to convert the image file to binary format.

The following is my code for reading images and converting them into binary format files in Ubuntu using Python + OpenCV.

#coding=utf-8
'''
Created on March 24, 2016
Use OpenCV to read the image, save it as a binary format file, and then read the binary file and convert it into an image for display
@author: hanchao
'''
import cv2
import numpy as np
import struct

image = cv2.imread("test.jpg")
#imageClone = np.zeros((image.shape[0],image.shape[1],1),np.uint8)

# image.shape [0] is rows
# image.shape [1] For cols
# image.shape [2] For channels
#image.shape = (480,640,3)
rows = image.shape[0]
cols = image.shape[1]
channels = image.shape[2]
#Convert image to binary file
#Write binary file in Python, f = open ('name ','wb')
#Only WB can write binary files
fileSave = open('patch.bin','wb')
for step in range(0,rows):
  for step2 in range(0,cols):
    fileSave.write(image[step,step2,2])
for step in range(0,rows):
  for step2 in range(0,cols):
    fileSave.write(image[step,step2,1])
for step in range(0,rows):
  for step2 in range(0,cols):
    fileSave.write(image[step,step2,0])
fileSave.close()
    
#Convert binary to image and display
#Python read binary files, using RB
#f. In read (n), n is the number of bytes that need to be read. After reading, it needs to be decoded struct.unpack ("B", fileReader.read (1) ) function
#Where "B" is an unsigned integer, accounting for one byte, "B" is a signed integer, accounting for one byte
#"C" is char type, occupying one byte
#"I" is int type, accounting for four bytes, I is signed integer, accounting for four bytes
#"H" and "H" are short types, accounting for four bytes, corresponding to signed and unsigned
#"L" and "L" are long types, accounting for four bytes, corresponding to signed and unsigned
fileReader = open('patch.bin','rb')
imageRead = np.zeros(image.shape,np.uint8)
for step in range(0,rows):
  for step2 in range(0,cols):
    a = struct.unpack("B",fileReader.read(1))
    imageRead[step,step2,2] = a[0]
for step in range(0,rows):
  for step2 in range(0,cols):
    a = struct.unpack("b",fileReader.read(1))
    imageRead[step,step2,1] = a[0]
for step in range(0,rows):
  for step2 in range(0,cols):
    a = struct.unpack("b",fileReader.read(1))
    imageRead[step,step2,0] = a[0]
    
fileReader.close()
cv2.imshow("source",image)
cv2.imshow("read",imageRead)
cv2.waitKey(0)

The above Python + opencv implementation of converting images to binary format is the whole content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developer more.