Python+OpenCV實現(xiàn)將圖像轉(zhuǎn)換為二進制格式
更新時間:2020年01月09日 15:14:33 作者:大蛇王
今天小編就為大家分享一篇Python+OpenCV實現(xiàn)將圖像轉(zhuǎn)換為二進制格式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
在學(xué)習(xí)tensorflow的過程中,有一個問題,tensorflow在訓(xùn)練的過程中讀取的是二進制圖像數(shù)據(jù)庫文件,而不是圖像文件,因此
在進行訓(xùn)練、測試之前需要將圖像文件轉(zhuǎn)換為二進制格式。
下面是我在ubuntu中使用python+OpenCV讀取圖像并轉(zhuǎn)換為二進制格式文件的代碼。
#coding=utf-8
'''
Created on 2016年3月24日
使用Opencv讀取圖像將其保存為二進制格式文件,再讀取該二進制文件,轉(zhuǎn)換為圖像進行顯示
@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]
#把圖像轉(zhuǎn)換為二進制文件
#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()
#把二進制轉(zhuǎn)換為圖像并顯示
#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é),分別對應(yīng)有符號、無符號
#“l(fā)”、“L”為long類型,占四個字節(jié),分別對應(yīng)有符號、無符號
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)將圖像轉(zhuǎn)換為二進制格式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
一篇文章帶你學(xué)習(xí)Python3的高級特性(1)
這篇文章主要為大家詳細介紹了Python3的高階函數(shù),主要介紹什么是高級特性,高級特性的用法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Python使用ntplib庫同步校準當(dāng)?shù)貢r間的方法
NTP網(wǎng)絡(luò)時間協(xié)議其實大家平時或多或少都能接觸到,包括Windows在內(nèi)的操作系統(tǒng)中的很多Internet時間同步功能都是在NTP的基礎(chǔ)上來做,這里我們來看一下Python使用ntplib庫同步校準當(dāng)?shù)貢r間的方法2016-07-07

