python实现彩色图转换成灰度图
程序员文章站
2022-06-20 14:38:34
本文实例为大家分享了python实现彩色图转换成灰度图的具体代码,供大家参考,具体内容如下
from pil import image
import os...
本文实例为大家分享了python实现彩色图转换成灰度图的具体代码,供大家参考,具体内容如下
from pil import image import os # 图像组成:红绿蓝 (rgb)三原色组成 亮度(255,255,255) image = "annie1.jpg" img = image.open(image) img_all = "素描" + image new = image.new("l", img.size, 255) width, height = img.size img = img.convert("l") # print(img.size) # print(img.mode) #rbg # # img_get = img.getpixel((0, 0)) # print(img_get) #三原色通道 # # img_l=img.convert('l') # print(img_l) # img_get_l=img_l.getpixel((0,0)) #换算 得到灰度值 # print(img_get_l) # 定义画笔的大小 pen_size = 3 # 色差扩散器 color_diff = 6 for i in range(pen_size + 1, width - pen_size - 1): for j in range(pen_size + 1, height - pen_size - 1): # 原始的颜色 originalcolor = 255 lcolor = sum([img.getpixel((i - r, j)) for r in range(pen_size)]) // pen_size rcolor = sum([img.getpixel((i + r, j)) for r in range(pen_size)]) // pen_size # 通道----颜料 if abs(lcolor - rcolor) > color_diff: originalcolor -= (255 - img.getpixel((i, j))) // 4 new.putpixel((i, j), originalcolor) ucolor = sum([img.getpixel((i, j - r)) for r in range(pen_size)]) // pen_size dcolor = sum([img.getpixel((i, j + r)) for r in range(pen_size)]) // pen_size # 通道----颜料 if abs(ucolor - dcolor) > color_diff: originalcolor -= (255 - img.getpixel((i, j))) // 4 new.putpixel((i, j), originalcolor) acolor = sum([img.getpixel((i - r, j - r)) for r in range(pen_size)]) // pen_size bcolor = sum([img.getpixel((i + r, j + r)) for r in range(pen_size)]) // pen_size # 通道----颜料 if abs(acolor - bcolor) > color_diff: originalcolor -= (255 - img.getpixel((i, j))) // 4 new.putpixel((i, j), originalcolor) qcolor = sum([img.getpixel((i + r, j - r)) for r in range(pen_size)]) // pen_size wcolor = sum([img.getpixel((i - r, j + r)) for r in range(pen_size)]) // pen_size # 通道----颜料 if abs(qcolor - wcolor) > color_diff: originalcolor -= (255 - img.getpixel((i, j))) // 4 new.putpixel((i, j), originalcolor) new.save(img_all) i = os.system('mshta vbscript createobject("sapi.spvoice").speak("%s")(window.close)' % '您的图片转换好了') os.system(img_all)
原图像:
转换后
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。