溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python+OpenCV實(shí)現(xiàn)將圖像轉(zhuǎn)換為二進(jìn)制格式

發(fā)布時(shí)間:2020-09-20 20:30:58 來源:腳本之家 閱讀:790 作者:大蛇王 欄目:開發(fā)技術(shù)

在學(xué)習(xí)tensorflow的過程中,有一個(gè)問題,tensorflow在訓(xùn)練的過程中讀取的是二進(jìn)制圖像數(shù)據(jù)庫文件,而不是圖像文件,因此

在進(jìn)行訓(xùn)練、測(cè)試之前需要將圖像文件轉(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”為無符號(hào)整數(shù),占一個(gè)字節(jié),“b”為有符號(hào)整數(shù),占1個(gè)字節(jié)
#“c”為char類型,占一個(gè)字節(jié)
#“i”為int類型,占四個(gè)字節(jié),I為有符號(hào)整形,占4個(gè)字節(jié)
#“h”、“H”為short類型,占四個(gè)字節(jié),分別對(duì)應(yīng)有符號(hào)、無符號(hào)
#“l(fā)”、“L”為long類型,占四個(gè)字節(jié),分別對(duì)應(yīng)有符號(hào)、無符號(hào)
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實(shí)現(xiàn)將圖像轉(zhuǎn)換為二進(jìn)制格式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI