马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import cv2
import os
import os.path
import numpy
def img2txt(img_path = r'C:\Users\LuvPeppa\Desktop\img_files\1',txt_name = 'new_test.txt'):
R = []
G = []
B = []
with open(txt_name,'w') as f:
for each_file in os.listdir(img_path):
#path = r'C:\Users\Wongtao\Desktop\Cifarpy\img_files\1'
if os.path.splitext(each_file)[1] == '.jpg':
image = cv2.imread(each_file)
p1=cv2.resize(image,(32,32),interpolation=cv2.INTER_CUBIC)
#each_data = numpy.reshape(p1,(32,32,3))
print('数组p1的形状是',numpy.shape(p1),type(p1))
for each_pix in p1:
for each_color in each_pix:
B.append(each_color[0])
G.append(each_color[1])
R.append(each_color[2])
new_data = list(R+G+B)
print('数组R的形状是%s'%numpy.shape(R))
print('数组new_data的形状是%s'%numpy.shape(new_data))
#for each_line in new_data:
new_data = str(new_data).replace(',',' ')
new_data = new_data.replace('[','')
new_data = new_data.replace(']','')
f.write(str(new_data)+'\n')
R = []
G = []
B = []
cv2.imshow('a',p1)
#cv2.imwrite('new_'+each_file,p1)#保存图片
print(p1)
break
def txt2img(txt_name = 'new_test.txt'):
with open(txt_name,'r') as f:
img_data = [];R = [];G = [];B =[];col = ['[',']']
img_mat = numpy.zeros((1024,3))
for each_line in f:
img_data = [];R = [];G = [];B =[];
print(type(each_line),len(each_line),'1')
#print(each_line)
print(type(each_line),len(each_line),'2')
each_line,nothing = each_line.split(sep = '\n')
each_line = each_line.split(sep = ' ')
print(type(each_line),len(each_line))
for each_color in each_line:
#if each_color not in col:
img_data.append(int(each_color))
R = numpy.array(img_data[0:1024])
G = numpy.array(img_data[1024:2048])
B = numpy.array(img_data[2048:3072])
#img_mat = numpy.array(numpy.hstack((B,G,R)))
for each in range(len(B)):
img_mat[each][0] = int(B[each])
img_mat[each][1] = int(G[each])
img_mat[each][2] = int(R[each])
#img_mat = img_mat.T
#print('B',type(B))
print(B[0],G[0],R[0])
print('%s的形状是%s,类型是%s'%('img_mat',numpy.shape(img_mat),type(img_mat)),img_mat[0])
cv2.imshow('a',numpy.reshape(img_mat,(32,32,3)))
print(img_mat)
break
if __name__ == '__main__':
img2txt()
txt2img()
这段代码段img2txt()可以将图片转换为txt文档,但是txt2img()没法将该文档显示成图片。
明明打印出来的图片数据都一样,请问这是什么原因呢? |