How to read images from a text file using openCV?
In OpenCV, the cv2.imread() function can be used to read image files. If the image file is saved in txt format, you can first read the txt file and then convert it to image data.
This is a simple example code that reads image data from a txt file and displays the image.
import numpy as np
import cv2
# 读取txt文件
with open('image.txt', 'r') as file:
data = file.read()
# 将txt文件中的数据转换为图片数据
image_data = np.array(list(map(int, data.split())), dtype=np.uint8)
image = image_data.reshape((100, 100))
# 显示图片
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
In this example, we assume that image data is stored in a txt file named image.txt, where the data is space-separated pixel values of the image. Starting by reading the contents of the txt file, then converting it into a one-dimensional NumPy array, followed by reshaping it into the dimensions of the image and displaying it.