python实现彩色图转换成灰度图

时间:2022-09-13 13:09:18

本文实例为大家分享了python实现彩色图转换成灰度图的具体代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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)

原图像:

python实现彩色图转换成灰度图

转换后

python实现彩色图转换成灰度图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Bancroft_boy/article/details/81209810