入门者大坑:已经都使用opencv库和python了,可以给一个简单粗暴的标准,一旦你使用了双重循环,则你的代码一定不够高效,最好是连循环都不要出现,所有需要循环的操作,都教给opencv或numpy的内置函数去做。
直接操作像素:getpixel()&putpixel()
读:img.getpixel((x, y)):传入坐标元组,返回像素值元组
写:img.putpixel((x, y), g_color):传入坐标元组和像素值元组
from PIL import Image# 处理像素的方法def gray(color):temp = int((color[0]+color[1]+color[2])/3)return (temp, temp, temp, color[3])img = Image.open(r'D:\1.png')img = img.convert('RGBA') # 修改颜色通道为RGBAwidth, height = img.sizeprint(img.size)for y in range(height):for x in range(width):color = img.getpixel((x, y)) # 获取像素值g_color = gray(color) # 处理像素img.putpixel((x, y), g_color) # 修改像素值# print(g_color, end="")# print(",", end="")# print("")img.save(r'D:\2.png')
图像转矩阵:numpy.asarray(image)
from PIL import Imageimport numpyimg = Image.open(r'D:\1.png')data=numpy.asarray(img) # 图像转矩阵print(data)
矩阵转图像:Image.fromarray(Array)
img=Image.fromarray(data) # 矩阵转图像img.save(r'D:\2.png')
