入门者大坑:已经都使用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') # 修改颜色通道为RGBA
width, height = img.size
print(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 Image
import numpy
img = 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')