前言
通过将图像转为txt格式的数据,是本人主页一些基于FPGA的图像处理的基础前提,本文给出基于python的格式转换,主要分为三部分,一是将彩色图像(RGB888)转为txt格式,二是将彩色图像(RGB888)的TXT格式的数据转换为JPG格式,三是将灰度图像的TXT格式数据转换为JPG格式。
代码
将彩色图像转变为txt
img = cv2.imread("1.jpg") #读取图像“1.jpg”
img = cv2.resize(img,(1280,720)) #将图像大小修改为1280*720
with open("img2txt.txt","w") as f: #打开“img2txt.txt”文件,然后将图像数据依次写入文件
for i in range(img.shape[0]):
for j in range(img.shape[1]):
f.write('%02x' % (img[i,j,2]))
f.write('%02x' % (img[i,j,1]))
f.write('%02x' % (img[i,j,0]))
f.write("\n")
将彩色图像(RGB888)的TXT格式的数据转换为JPG格式
w = 1280 #图像像素宽度
h = 720 #图像像素高度
c = 3 #图像通道数
with open("txt2img.txt",'rb') as f:
data = [(int(line.strip(),16)) for line in f]
img_array = np.zeros((h,w,c), dtype = np.uint8)
for i in range(h):
for j in range(w):
img_array[i,j,0] = (data[i * w + j] & 0x00_00_ff) >>0
img_array[i,j,1] = (data[i * w + j] & 0x00_ff_00) >>8
img_array[i,j,2] = (data[i * w + j] & 0xff_00_00) >>16
cv2.imwrite("txt2img.jpg",img_array)
将灰度图像的TXT格式数据转换为JPG格式
w = 1280
h = 720
c = 1
with open("txt2img.txt",'rb') as f:
data = [(int(line.strip(),16)) for line in f]
img_array = np.zeros((h,w,c), dtype = np.uint8)
for i in range(h):
for j in range(w):
img_array[i,j,0] = data[i * w + j]
cv2.imwrite("txt2img.jpg",img_array)
完整代码
import cv2
import numpy as np
def img2txt(img_path):
txt_path = "img2txt.txt"
img = cv2.imread(img_path)
img = cv2.resize(img,(1280,720))
with open(txt_path,"w") as f:
for i in range(img.shape[0]):
for j in range(img.shape[1]):
f.write('%02x' % (img[i,j,2]))
f.write('%02x' % (img[i,j,1]))
f.write('%02x' % (img[i,j,0]))
f.write("\n")
def txt2img(txt_path):
img_path = "txt2img.jpg"
w = 1280
h = 720
c = 3
with open(txt_path,'rb') as f:
data = [(int(line.strip(),16)) for line in f]
img_array = np.zeros((h,w,c), dtype = np.uint8)
for i in range(h):
for j in range(w):
img_array[i,j,0] = (data[i * w + j] & 0x00_00_ff) >>0
img_array[i,j,1] = (data[i * w + j] & 0x00_ff_00) >>8
img_array[i,j,2] = (data[i * w + j] & 0xff_00_00) >>16
cv2.imwrite(img_path,img_array)
def txt2grayimg(txt_path):
img_path = "txt2grayimg.jpg"
w = 1280
h = 720
c = 1
with open(txt_path,'rb') as f:
data = [(int(line.strip(),16)) for line in f]
img_array = np.zeros((h,w,c), dtype = np.uint8)
for i in range(h):
for j in range(w):
img_array[i,j,0] = data[i * w + j]
cv2.imwrite(img_path,img_array)
#img2txt("1.jpg")
#txt2img("D:/pic/fileout_yuv.txt")
txt2grayimg("D:/pic/fileout_gray.txt")
结语
都是最基础的操作,注意路径正确就好