Python 读取 PGM 格式图片,RGB 转 PGM
程序员文章站
2022-03-19 23:44:17
...
首先了解一下PGM格式:
Python 读取 PGM 格式图片
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
def read_img_p5(im1_path):
im1 = Image.open(im1_path)
im1.show()
print(im1.size)
def read_img_p2(im2):
with open(im2) as f:
lines = f.readlines()
for l in list(lines):
if l[0] == '#':
lines.remove(l)
assert lines[0].strip() == 'P2'
data = []
for line in lines[1:]:
data.extend([int(c) for c in line.split()])
plt.imshow(np.reshape(np.array(data[3:]), (data[1], data[0])), cmap=plt.cm.gray_r)
plt.show()
if __name__ == "__main__":
im1_path = "./1.pgm" # 你的 P5 PGM 文件路径
im2_path = "./2.pgm" # 你的 P2 PGM 文件路径
read_img_p5(im1_path)
read_img_p2(im2_path)
如果读错文件,比如使用 read_img_p5 函数读取了 p2 型 PGM 文件,那么会报这种错误:
FileNotFoundError: [Errno 2] No such file or directory: .................
Python RGB 转 PGM
from PIL import Image
from Open_pgm import read_img_p5
import os.path
def jpg2pgm(jpg_file, pgm_dir):
jpg = Image.open(jpg_file)
jpg = jpg.convert('L')
jpg.show()
jpg = jpg.resize((1920, 1080), Image.BILINEAR)
name = (str)(os.path.join(pgm_dir, os.path.splitext(os.path.basename(jpg_file))[0])) + ".pgm"
jpg.save(name)
return name
if __name__ == "__main__":
jpg_im_path = "./1.jpg" # 你的 jpg 格式图片文件路径
pgm_imfile_path = "./pgm" # 你的 pgm 格式图片文件存放文件夹
pgm_im_path = jpg2pgm(jpg_im_path, pgm_imfile_path)
read_img_p5(pgm_im_path)
上一篇: iPhone12起步价过高,还要购买昂贵的配件,让消费者失望
下一篇: php流程控制语句