在學習tensorflow的過程中,有一個問題,tensorflow在訓練的過程中讀取的是二進制圖像數據庫文件,而不是圖像文件,因此
在進行訓練、測試之前需要將圖像文件轉換為二進制格式。
下面是我在ubuntu中使用python+OpenCV讀取圖像并轉換為二進制格式文件的代碼。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
#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是需要讀取的字節數,讀取后需要進行解碼,使用struct.unpack("B",fileReader.read(1))函數 #其中“B”為無符號整數,占一個字節,“b”為有符號整數,占1個字節 #“c”為char類型,占一個字節 #“i”為int類型,占四個字節,I為有符號整形,占4個字節 #“h”、“H”為short類型,占四個字節,分別對應有符號、無符號 #“l”、“L”為long類型,占四個字節,分別對應有符號、無符號 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實現將圖像轉換為二進制格式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/t8116189520/article/details/78889327