将 txt 文件中的 jpeg 值转换为图像
Convert jpeg values in txt file to image
我正在尝试在此代码中将 txt 文件中的 jpeg 值转换为 jpg 图像。
截取的图片大小=120*160,文件中的值个数=2396(不知道为什么总长这么大)
我收到这个错误
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
ValueError: cannot reshape array of size 2396 into shape (120,160)
代码:
# Open image file, slurp the lot
contents = Path('C://Users//hp//Desktop//file.txt').read_text()
# Make a list of anything that looks like numbers using a regex...
# ... taking first as height, second as width and remainder as pixels
h, w, *pixels = re.findall(r'[0-9]+', contents)
# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save('C://Users//hp//Desktop//jp.jpg')
不需要PIL库。您已有 JPEG 文件。
只需将这些数字转换为字节并保存即可。
with open("C://Users//hp//Desktop//file.txt", "r") as f:
data = f.read()
data = data.split(",") # split the numbers
data = [int(b) for b in data] # convert them to integers
data = data[2:] # remove width and height
data = bytes(data) # convert the array of numbers to bytes
with open("C://Users//hp//Desktop//jp.jpg", "wb") as f:
f.write(data)
结果:
注意:末尾似乎缺少数据。您可能没有捕获所有数据。
你声称有 2396 个值,但你的示例有 3842 个。
我正在尝试在此代码中将 txt 文件中的 jpeg 值转换为 jpg 图像。 截取的图片大小=120*160,文件中的值个数=2396(不知道为什么总长这么大)
我收到这个错误
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
ValueError: cannot reshape array of size 2396 into shape (120,160)
代码:
# Open image file, slurp the lot
contents = Path('C://Users//hp//Desktop//file.txt').read_text()
# Make a list of anything that looks like numbers using a regex...
# ... taking first as height, second as width and remainder as pixels
h, w, *pixels = re.findall(r'[0-9]+', contents)
# Now make pixels into Numpy array of uint8 and reshape to correct height, width and depth
na = np.array(pixels, dtype=np.uint8).reshape((int(h),int(w)))
# Now make the Numpy array into a PIL Image and save
Image.fromarray(na).save('C://Users//hp//Desktop//jp.jpg')
不需要PIL库。您已有 JPEG 文件。
只需将这些数字转换为字节并保存即可。
with open("C://Users//hp//Desktop//file.txt", "r") as f:
data = f.read()
data = data.split(",") # split the numbers
data = [int(b) for b in data] # convert them to integers
data = data[2:] # remove width and height
data = bytes(data) # convert the array of numbers to bytes
with open("C://Users//hp//Desktop//jp.jpg", "wb") as f:
f.write(data)
结果:
注意:末尾似乎缺少数据。您可能没有捕获所有数据。
你声称有 2396 个值,但你的示例有 3842 个。