Python+OpenCV實現(xiàn)將圖像轉(zhuǎn)換為二進(jìn)制格式
在學(xué)習(xí)tensorflow的過程中,有一個問題,tensorflow在訓(xùn)練的過程中讀取的是二進(jìn)制圖像數(shù)據(jù)庫文件,而不是圖像文件,因此
在進(jìn)行訓(xùn)練、測試之前需要將圖像文件轉(zhuǎn)換為二進(jìn)制格式。
下面是我在ubuntu中使用python+OpenCV讀取圖像并轉(zhuǎn)換為二進(jìn)制格式文件的代碼。
#coding=utf-8 ''' Created on 2016年3月24日 使用Opencv讀取圖像將其保存為二進(jìn)制格式文件,再讀取該二進(jìn)制文件,轉(zhuǎn)換為圖像進(jì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)換為二進(jìn)制文件 #python寫二進(jìn)制文件,f = open('name','wb') #只有wb才是寫二進(jìn)制文件 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() #把二進(jìn)制轉(zhuǎn)換為圖像并顯示 #python讀取二進(jìn)制文件,用rb #f.read(n)中n是需要讀取的字節(jié)數(shù),讀取后需要進(jìn)行解碼,使用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)換為二進(jìn)制格式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python實現(xiàn)整數(shù)的二進(jìn)制循環(huán)移位
- 一篇教程教你學(xué)會Python進(jìn)制轉(zhuǎn)換(十進(jìn)制轉(zhuǎn)二進(jìn)制、八進(jìn)制、十六進(jìn)制)
- Python 字符串與二進(jìn)制串的相互轉(zhuǎn)換示例
- Python二進(jìn)制串轉(zhuǎn)換為通用字符串的方法
- python十進(jìn)制和二進(jìn)制的轉(zhuǎn)換方法(含浮點數(shù))
- Python 內(nèi)置函數(shù)進(jìn)制轉(zhuǎn)換的用法(十進(jìn)制轉(zhuǎn)二進(jìn)制、八進(jìn)制、十六進(jìn)制)
- Python 中將二進(jìn)制轉(zhuǎn)換為整數(shù)的多種方法
相關(guān)文章
一篇文章帶你學(xué)習(xí)Python3的高級特性(1)
這篇文章主要為大家詳細(xì)介紹了Python3的高階函數(shù),主要介紹什么是高級特性,高級特性的用法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01Python使用ntplib庫同步校準(zhǔn)當(dāng)?shù)貢r間的方法
NTP網(wǎng)絡(luò)時間協(xié)議其實大家平時或多或少都能接觸到,包括Windows在內(nèi)的操作系統(tǒng)中的很多Internet時間同步功能都是在NTP的基礎(chǔ)上來做,這里我們來看一下Python使用ntplib庫同步校準(zhǔn)當(dāng)?shù)貢r間的方法2016-07-07