python3 实现验证码图片切割的方法

时间:2022-06-05 01:32:31

切割前图片

python3 实现验证码图片切割的方法

切割后四个图片

python3 实现验证码图片切割的方法

代码

?
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
#coding:utf8
import os
from pil import image,imagedraw,imagefile
import numpy
import pytesseract
import cv2
import imagehash
import collections
class pictureidenti:
 
 #rownum:切割行数;colnum:切割列数;dstpath:图片文件路径;img_name:要切割的图片文件
 def splitimage(self, rownum=1, colnum=4, dstpath="d:\work\python36_crawl\veriycode",
     img_name="d:\work\python36_crawl\veriycode\mode_5246.png",):
  img = image.open(img_name)
  w, h = img.size
  if rownum <= h and colnum <= w:
   print('original image info: %sx%s, %s, %s' % (w, h, img.format, img.mode))
   print('开始处理图片切割, 请稍候...')
 
   s = os.path.split(img_name)
   if dstpath == '':
    dstpath = s[0]
   fn = s[1].split('.')
   basename = fn[0]
   ext = fn[-1]
 
   num = 1
   rowheight = h // rownum
   colwidth = w // colnum
   file_list = []
   for r in range(rownum):
    index = 0
    for c in range(colnum):
     # (left, upper, right, lower)
     # box = (c * colwidth, r * rowheight, (c + 1) * colwidth, (r + 1) * rowheight)
     if index<1:
      colwid = colwidth+6
     elif index<2:
      colwid = colwidth + 1
     elif index < 3:
      colwid = colwidth
 
     box = (c * colwid, r * rowheight, (c + 1) * colwid, (r + 1) * rowheight)
     newfile = os.path.join(dstpath, basename + '_' + str(num) + '.' + ext)
     file_list.append(newfile)
     img.crop(box).save(os.path.join(dstpath, basename + '_' + str(num) + '.' + ext), ext)
     num = num + 1
     index+=1
   for f in file_list:
    print(f)
   print('图片切割完毕,共生成 %s 张小图片。' % num)

以上这篇python3 实现验证码图片切割的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/shaosks/p/9700610.html