入门者大坑:已经都使用opencv库和python了,可以给一个简单粗暴的标准,一旦你使用了双重循环,则你的代码一定不够高效,最好是连循环都不要出现,所有需要循环的操作,都教给opencv或numpy的内置函数去做。

*以下是错误示范,不应当使用python循环

直接操作像素:getpixel()&putpixel()

读:img.getpixel((x, y)):传入坐标元组,返回像素值元组
写:img.putpixel((x, y), g_color):传入坐标元组和像素值元组

  1. from PIL import Image
  2. # 处理像素的方法
  3. def gray(color):
  4. temp = int((color[0]+color[1]+color[2])/3)
  5. return (temp, temp, temp, color[3])
  6. img = Image.open(r'D:\1.png')
  7. img = img.convert('RGBA') # 修改颜色通道为RGBA
  8. width, height = img.size
  9. print(img.size)
  10. for y in range(height):
  11. for x in range(width):
  12. color = img.getpixel((x, y)) # 获取像素值
  13. g_color = gray(color) # 处理像素
  14. img.putpixel((x, y), g_color) # 修改像素值
  15. # print(g_color, end="")
  16. # print(",", end="")
  17. # print("")
  18. img.save(r'D:\2.png')

*以下方法处理大图会失败溢出且处理速度极慢效率极差

图像转矩阵:numpy.asarray(image)

  1. from PIL import Image
  2. import numpy
  3. img = Image.open(r'D:\1.png')
  4. data=numpy.asarray(img) # 图像转矩阵
  5. print(data)

矩阵转图像:Image.fromarray(Array)

  1. img=Image.fromarray(data) # 矩阵转图像
  2. img.save(r'D:\2.png')