python写一个ppm图片查看器

首先,如果要绘制图像,需要导入graphics模块。

打开文件是必须的。

接下来,需要读取前三行,第一行是标准格式,第二行是宽度和高度,第三行是最大亮度值。

我们用空列表来存储其余的部分,也就是RGB值,三个值为一组(元组),每一组代表一个像素也就是一个颜色。

把RGB值转换成图像代码,然后输出。

from graphics import graphics   # 导入graphics模块
     
def main():   # 主函数
    image = open('tt.ppm', 'r')   # 打开图片文件
    image_format = image.readline().strip()   # 读取图片格式
    width_height = image.readline().strip().split(' ')   # 读取图片宽度和高度
    width = int(width_height[0])   # 提取宽度,保存为整数
    height = int(width_height[1])   # 提取高度,保存为整数
    max_rgb = int(image.readline())   # 读取最大RGB值
     
    full_image = []   # 建立空列表
    for line in image:   # 读取每一行
        line = line.strip().split()   # 去除空格和换行符,并分割为列表
        row = []   # 建立空列表     
        for i in range(0, len(line), 3):    # 循环读取RGB值,每3个值一组
            pixel = ( int(line[i]), int(line[i+1]), int(line[i+2]))   # 建立元组,保存RGB值
            row.append(pixel)   # 追加元组到列表
        full_image.append(row)   # 追加列表到列表
     
    scale = float(input('图像设置多大? '))   # 读取缩放比例,建议100
    gui = graphics(width * scale, height * scale, 'PPM图像查看器')   # 建立GUI窗口,设置大小和标题
    for row in range(len(full_image)):   # 循环绘制每一行
        for column in range(len(full_image[row])):   # 循环绘制每一列
            pixel = full_image[row][column]   # 读取当前像素
            color = gui.get_color_string(pixel[0], pixel[1], pixel[2])   # 转换为颜色字符串,如#003264
            gui.rectangle(column * scale, row * scale, scale, scale, color)   # 绘制矩形,设置位置和大小,颜色
    gui.draw()   # 显示图像

main()   # 调用主函数

结果为扩大了100倍的ppm图像。

评论

发表评论

了解 数据控|突破是我们的每一步 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读