python读取像素值

记录一下利用python读取像素值,并将像素值保存在txt文档中,可使用matlab将txt文档转换为像素矩阵。
代码如下:

#将mask图转换为像素值,并生成txt文档,以便于matlab读取
import os
from PIL import Image
filename = os.listdir('G:/1/2/3/4')
base_dir = ('G:/1/2/3/4/')
new_dir  = ('G:/1/2/3/4/')
for img in filename:
    txt_name = img.split('.')[0]
    new_txt_name = txt_name + '.txt'
    f2 = open(new_dir + new_txt_name,'w+')
    image=Image.open((base_dir + img))
    w1 = image.size[0]#行
    h1 = image.size[1]#列
    image_new=image.convert("P")
    for i in range(w1):
        for j in range(h1):
            xs = image_new.getpixel((i,j))
            print(xs,file=f2)

如果是读为RGB格式的,代码如下:

import os
from PIL import Image
filename = os.listdir('G:/1/2/3/4')
base_dir = ('G:/1/2/3/4/')
new_dir  = ('G:/1/2/3/4/')
for img in filename:
    txt_name = img.split('.')[0]
    new_txt_name = txt_name + '.txt'
    f2 = open(new_dir + new_txt_name,'w+')
    image=Image.open((base_dir + img))
    w1 = image.size[0]#行
    h1 = image.size[1]#列
	image_new = image.convert('RGB')
	for i in range(w1):
		for j in range(h1):
			xs = image_new.getpixel((i,j))
			print(xs,file=f2)

你可能感兴趣的:(python,python,matlab,计算机视觉,图像处理)