脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 处理图片像素点的实例

Python 处理图片像素点的实例

2021-05-12 00:36seTaire Python

今天小编就为大家分享一篇Python 处理图片像素点的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

###在做爬虫的时候有时需要识别验证码,但是验证码一般都有干扰物,这时需要对验证码进行预处理,效果如下:

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
from PIL import Image
import itertools
img = Image.open('C:/img.jpg').convert('L') #打开图片,convert图像类型有L,RGBA
 
# 转化为黑白图
def blackWrite(img):
 blackXY = []
 
 # 遍历像素点
 for x in range(img.size[0]):
  for y in range(img.size[1]):
   print img.getpixel((x,y))
   if img.getpixel((x,y))<128:
    img.putpixel((x,y),0) # 置为黑点
    blackXY.append((x,y))
   else:
    img.putpixel((x,y),255) # 置为白点
 return blackXY
 
 
# 去除干扰点
def clrImg(img,pointArr):
 # 获取周围黑点的个数
 def getN(p):
  count = 0
  x = [p[0]-1,p[0],p[0]+1]
  y = [p[1]-1,p[1],p[1]+1]
  for i in itertools.product(x,y): # 笛卡尔积
   try:
    if img.getpixel(i) == 0:
     count +=1
   except:
    print 'out of'
    continue
  print count
  return count
 
 for p in pointArr:
  if getN(p)<5: # 周围黑点个数 <5 的黑点认为是干扰点,置为白点
   img.putpixel(p,255)
   
pointArr = blackWrite(img)
clrImg(img,pointArr)
img.save("C:/img_1.jpg")

以上这篇Python 处理图片像素点的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/seTaire/article/details/78578506

延伸 · 阅读

精彩推荐