首页 > 编程问答 >将 pgm 转换为 png

将 pgm 转换为 png

时间:2024-07-20 23:19:51浏览次数:6  
标签:python image png pgm

我的文件夹中有 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

相关文章

  • ModuleNotFoundError:没有名为“pyaes”的模块 python 虚拟机
    在此处输入图像描述当我在启动python项目的虚拟机上构建某个工具时,几秒钟后会出现此消息。我已经尝试重新安装pyaes但无济于事。谁能帮我?非常感谢我已经尝试重新安装pyaes但无济于事,我搜索了tepyaes模块的十个路径,但我没有找到它,而我在另一台虚拟机上完成了......
  • 如何通过 mutagen (Python) 为 mp3 文件中的情绪添加价值?
    我找不到通过mutagen(Python库)将情绪写入mp3文件的方法初始化:frommutagen.mp3importMP3frommutagen.id3importID3,TIT2,TALB,TPE1,TPE2,TCON,TPUB,TENC,TIT3,APIC,WOAR,PRIVaudio=MP3(mp3_file,ID3=ID3)我可以使用audio['TIT3']=TIT3(......
  • 使用 Python 操作 Splunk
    使用Python操作Splunk目录使用Python操作Splunk1参考文档2安装PythonSplunk-SDK3连接splunk4配置查询5参考1参考文档SplunkGithub地址:GitHub-splunk/splunk-sdk-python:SplunkSoftwareDevelopmentKitforPythonSplunk开发者文档地址:Pythontools|......
  • Python:如何通过请求帖子对评论进行投票?
    我对评论进行投票的代码无法正常工作。它返回一个http500错误。我有一个使用用户登录的Python程序,它应该自动对评论进行投票。我的代码如下:frombs4importBeautifulSoupimportrequestslogin_url="https://xxxxxxxxxxx/auth/login"login_url_post="http......
  • python_day7(补1)
    数据类型​ 之前为列表类型​ 插入一个元组的介绍 之后还有字典,三者区别为括号方式()[]{}元组类型(tuple)使用:先定义一个元组数据​ vegetable_tuple='(tomato','corn','cucumber','carrot','corn','pumpkin)'与列表类型格式很像,不过只能取不能改,需要特......
  • 在 python 中写入 %appdata% 时出现奇怪的行为
    我试图将一些数据写入%appdata%。一切似乎都像Script1的输出中所示的那样工作。正在创建新目录并保存文件,并且也成功检索数据。但尝试查看文件资源管理器中的数据时,该文件夹不存在!CMD也找不到文件和目录。后来我手动创建了文件,检查了一下,发生了什么。CMD现在可以找到该文......
  • 使用 selenium 在 python 中打开 chrome 中的链接
    通过此链接https://bancadatistatisticaoas.inail.it/analytics/saw.dll?Dashboard&PortalPath=%2Fshared%2FBDS%2F_portal%2FINF_Definiti_Industria_e_Servizi我需要单击“FCostruzioni”,然后单击F41COSTRUZIONIED埃迪菲西。这是我的代码,但它不起作用。我做错了......
  • 七大排序算法的Python实现
    七大排序算法的Python实现1.冒泡排序(BubbleSort)算法思想冒泡排序通过重复交换相邻的未按顺序排列的元素来排序数组。每次迭代都将最大的元素“冒泡”到数组的末尾。复杂度分析时间复杂度:O(n^2)空间复杂度:O(1)defbubble_sort(arr):n=len(arr)for......
  • python反序列化
    之前hgame中遇到python反序列化,这次正好借分享会来尽可能详细学习一下python反序列化基础知识什么是序列化?反序列化?在很多时候为了方便对象传输,我们往往会把一些内容转化成更方便存储、传输的形式。我们把“对象->字符串”的翻译过程称为“序列化”;相应地,把“字符串->对......
  • 我在 python 项目中不断收到“无法识别图像文件中的数据”错误
    我正在尝试向我的TK窗口添加一个图标,但我不断收到一条错误消息:Traceback(mostrecentcalllast):File"C:\Users\roger\source\repos\PythonApplication\PythonApplication.py",line7,in<module>windowIcon=tk.PhotoImage(file="C:/Users/roger/Downloa......