我的文件夹中有 100 个 pgm 图像,我想将这些图像转换为 png 格式。我使用了这段代码,但是当我打开它时,结果图像要么是黑色的,要么只是正确构建的图像的一部分,而其他部分是黑色的: 我使用了这段代码,但是还有其他想法来转换这些图像吗?
import os
from PIL import Image
def convert_pgm_to_png(pgm_path, png_path):
# Open the PGM image in binary mode
with open(pgm_path, 'rb') as f:
# Read the header to extract image dimensions
header = f.readline().decode('latin-1').strip()
if header.startswith('P5'):
# Split the header line to extract width, height, and maximum gray value
dimensions = header.split()[1:]
width, height = map(int, dimensions[:2])
# Validate the maximum gray value
max_gray_value = int(dimensions[2])
if max_gray_value > 255:
raise ValueError('Invalid PGM file format. Maximum gray value exceeds 255.')
# Read the binary data
data = f.read()
else:
raise ValueError('Invalid PGM file format. Magic number is not "P5".')
# Convert binary data to a list of pixel values
pixels = list(data)
print(f"Pixel values: {pixels}") # Print the pixel values
# Create a new PIL Image object with appropriate mode and size
image = Image.new('L', (width, height))
# Assign the pixel values to the image
image.putdata(pixels)
# Save the image as PNG in the destination directory
image.save(png_path)
# Source directory containing PGM images
source_directory = "C:\\Users\\Sara\\Desktop\\dataasets\\Newfolder\\lr(compressed)_pgm"
# Destination directory to save PNG images
destination_directory = "C:\\Users\\Sara\\Desktop\\dataasets\\Newfolder\\lr\\"
# Iterate over all files in the source directory
for filename in os.listdir(source_directory):
if filename.endswith('.pgm'):
# Create the input file path for PGM image
pgm_file = os.path.join(source_directory, filename)
# Create the output file path for PNG image in the destination directory
png_file = os.path.join(destination_directory, os.path.splitext(filename)[0] + '.png')
try:
# Convert PGM to PNG
convert_pgm_to_png(pgm_file, png_file)
except ValueError as e:
header = ""
with open(pgm_file, 'rb') as f:
header = f.readline().decode('latin-1').strip()
print(f"Error converting {pgm_file}: {str(e)}")
问题出在读取二进制图像数据的方式上。虽然
f.read()
读取了所有剩余的字节,但在某些情况下,PGM 文件中可能存在注释或空格,这些注释或空格会干扰像素数据的读取。
请尝试使用此改进的代码:
import os
from PIL import Image
def convert_pgm_to_png(pgm_path, png_path):
"""将 PGM 图像转换为 PNG 图像。"""
with open(pgm_path, 'rb') as f:
header = f.readline().decode('latin-1').strip()
if header.startswith('P5'):
width, height, max_gray_value = map(int, f.readline().decode('latin-1').split())
if max_gray_value > 255:
raise ValueError('Invalid PGM file format. Maximum gray value exceeds 255.')
# 读取二进制图像数据,跳过注释和空格
image_data = bytearray()
while len(image_data) < width * height:
byte = f.read(1)
if byte not in (b'#', b' ', b'\t', b'\n', b'\r'):
image_data += byte
else:
raise ValueError('Invalid PGM file format. Magic number is not "P5".')
# 创建图像并保存
image = Image.frombytes('L', (width, height), bytes(image_data))
image.save(png_path)
# 源目录和目标目录
source_directory = "C:\\Users\\Sara\\Desktop\\dataasets\\Newfolder\\lr(compressed)_pgm"
destination_directory = "C:\\Users\\Sara\\Desktop\\dataasets\\Newfolder\\lr\\"
# 转换所有 PGM 文件
for filename in os.listdir(source_directory):
if filename.endswith('.pgm'):
pgm_file = os.path.join(source_directory, filename)
png_file = os.path.join(destination_directory, os.path.splitext(filename)[0] + '.png')
try:
convert_pgm_to_png(pgm_file, png_file)
except ValueError as e:
print(f"Error converting {pgm_file}: {str(e)}")
此代码通过逐字节读取图像数据,并跳过任何注释或空格,确保读取正确的像素值,从而解决了问题。
标签:python,image,png,pgm From: 78773118