Python+OpenCV實現(xiàn)將圖像轉換為二進制格式
更新時間:2020年01月09日 15:14:33 作者:大蛇王
今天小編就為大家分享一篇Python+OpenCV實現(xiàn)將圖像轉換為二進制格式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
在學習tensorflow的過程中,有一個問題,tensorflow在訓練的過程中讀取的是二進制圖像數(shù)據(jù)庫文件,而不是圖像文件,因此
在進行訓練、測試之前需要將圖像文件轉換為二進制格式。
下面是我在ubuntu中使用python+OpenCV讀取圖像并轉換為二進制格式文件的代碼。
#coding=utf-8
'''
Created on 2016年3月24日
使用Opencv讀取圖像將其保存為二進制格式文件,再讀取該二進制文件,轉換為圖像進行顯示
@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]為rows
#image.shape[1]為cols
#image.shape[2]為channels
#image.shape = (480,640,3)
rows = image.shape[0]
cols = image.shape[1]
channels = image.shape[2]
#把圖像轉換為二進制文件
#python寫二進制文件,f = open('name','wb')
#只有wb才是寫二進制文件
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()
#把二進制轉換為圖像并顯示
#python讀取二進制文件,用rb
#f.read(n)中n是需要讀取的字節(jié)數(shù),讀取后需要進行解碼,使用struct.unpack("B",fileReader.read(1))函數(shù)
#其中“B”為無符號整數(shù),占一個字節(jié),“b”為有符號整數(shù),占1個字節(jié)
#“c”為char類型,占一個字節(jié)
#“i”為int類型,占四個字節(jié),I為有符號整形,占4個字節(jié)
#“h”、“H”為short類型,占四個字節(jié),分別對應有符號、無符號
#“l(fā)”、“L”為long類型,占四個字節(jié),分別對應有符號、無符號
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)
以上這篇Python+OpenCV實現(xiàn)將圖像轉換為二進制格式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python使用ntplib庫同步校準當?shù)貢r間的方法
NTP網(wǎng)絡時間協(xié)議其實大家平時或多或少都能接觸到,包括Windows在內的操作系統(tǒng)中的很多Internet時間同步功能都是在NTP的基礎上來做,這里我們來看一下Python使用ntplib庫同步校準當?shù)貢r間的方法2016-07-07

