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

yipeiwu_com5年前Python基础

切割前图片

python3 验证码图片切割

切割后四个图片

python3 验证码图片切割

代码

#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 实现验证码图片切割的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python性能优化的20条建议

优化算法时间复杂度 算法的时间复杂度对程序的执行效率影响最大,在Python中可以通过选择合适的数据结构来优化时间复杂度,如list和set查找某一个元素的时间复杂度分别是O(n)和O(...

python统计文本文件内单词数量的方法

本文实例讲述了python统计文本文件内单词数量的方法。分享给大家供大家参考。具体实现方法如下: # count lines, sentences, and words of a t...

Python堆排序原理与实现方法详解

Python堆排序原理与实现方法详解

本文实例讲述了Python堆排序原理与实现方法。分享给大家供大家参考,具体如下: 在这里要事先说明一下我也是新手,很多东西我了解不是很深入,写算法完全是锻炼自己逻辑能力同时顺带帮助读研的...

python中while循环语句用法简单实例

本文实例讲述了python中while循环语句用法。分享给大家供大家参考。具体如下: number = 1 while number < 20: print(number)...

详解使用django-mama-cas快速搭建CAS服务的实现

详解使用django-mama-cas快速搭建CAS服务的实现

当公司有多条产品线,或者有多个不同的应用的时候,每次都做登录是个非常烦人的事情。(原谅我没有从SSO的角度看这个问题。。对我来说能偷懒少写点东西最实在)。为什么需要每次都做个登录?做登录...