验证码去噪

一、全局阈值二值化、8领域去噪法 

from PIL import Image, ImageDraw

def saveImage(t2val,Path):
    width=len(t2val);height=len(t2val[0])
    img = Image.new("1", (width,height))
    draw = ImageDraw.Draw(img)
    for x in range(width):
        for y in range(0, height):
            draw.point((x, y), t2val[x][y])
    img.save(Path)

def clearNoiseAndSave( G,t2val,Path):   # G为8领域去噪法阈值
    width = len(t2val);height = len(t2val[0])
    t2val[0][0] = t2val[width - 1][height - 1] = 1

    for x in range(1, width - 1):    # 去噪过程
        for y in range(1, height - 1):
            nearDots = 0
            L = t2val[x][y]
            if L == t2val[x - 1][y - 1]:
                nearDots += 1
            if L == t2val[x - 1][y]:
                nearDots += 1
            if L == t2val[x - 1][y + 1]:
                nearDots += 1
            if L == t2val[x][y - 1]:
                nearDots += 1
            if L == t2val[x][y + 1]:
                nearDots += 1
            if L == t2val[x + 1][y - 1]:
                nearDots += 1
            if L == t2val[x + 1][y]:
                nearDots += 1
            if L == t2val[x + 1][y + 1]:
                nearDots += 1
            # t2val[x][y]=L if nearDots>N else (L+1)%2
            if nearDots <= G:
                t2val[x][y] = 1
    saveImage(t2val,Path)

def convert_code(img,G,tvPath):     # G为二值化阈值
    t2val=[[0] * img.size[1] for i in range(img.size[0])]
    for x in range(0, img.size[0]): # 二值化过程
        for y in range(0, img.size[1]):
            g= img.getpixel((x, y))
            if g>G:
                t2val[x][y]=1
            else:
                t2val[x][y]=0
    saveImage(t2val,Path+'_tv.jpg')
    clearNoiseAndSave( 1,t2val,Path+'_CN.jpg')

if __name__ == '__main__':
    for i in range(5):       # 处理5张验证码
        Path = r'E:\User\xuDir\codes\photo%s' % (str(i))
        img = Image.open(Path+'.jpg').convert('L')
        convert_code(img,240,Path)

    print("OK!")   

 二值化后  photo0_tv.jpg  photo1_tv.jpg

 8领域去噪后 photo0_CN.jpg photo1_CN.jpg 

二、连通域去噪法  cv2skimage 

import cv2
from skimage import morphology

for i in range(5):     # 处理5张验证码
    Path = r'E:\User\xuDir\codes\photo%s.jpg' % (str(i))
    img = cv2.imread(Path, 1)
    img_gray = cv2.cvtColor(img ,cv2.COLOR_BGR2GRAY)                 # 格式转换灰度化
    ret, img_tv = cv2.threshold(img_gray, 240, 255, cv2.THRESH_BINARY_INV)   # 二值化
    cv2.imwrite(Path + '_cv2tv.jpg', img_tv)
                                                # 连通域去噪
    img_temp = morphology.remove_small_objects(img_tv.astype(bool), min_size=80, connectivity=1)
    for x in range(len(img_tv)):
        for y in range(len(img_tv[0])):
            img_tv[x][y] = 255 if img_temp[x][y] == False else 0
    cv2.imwrite(Path+'_cv2CN.jpg',img_tv) 

 morphology.remove_small_objects 把连通域小于80个像素点的True值都转为False;connectivity=1 4连通,connectivity=2 8连通

 二值化后  photo0_cv2tv.jpg photo1_cv2tv.jpg

 连通域去噪法 photo_cv2CN.jpg photo1_cv2CN.jpg


 三、opencv-python常用处理

安装库  pip install opencv-python 或 pip install -i https://mirrors.aliyun.com/pypi/simple/ opencv-python 或更改阿里镜像 

import cv2
img = cv2.imread('photo1.jpg', 1) cv2.imshow('somename', img) k = cv2.waitKey(0) & 0xFF if k == 27: # wait for ESC key to exit cv2.destroyAllWindows() elif k == ord('s'):    # wait for 's' key to save and exit cv2.imwrite('cat0.png',img) cv2.destroyAllWindows()     

 imread()的第二个参数取1表示JPG,取0表示灰度图,取-1表示JPEG

 img类型是<class 'numpy.ndarray'> ,这里它是一个三维数组[height][width][3] ,可通过print(img.shape) -> (600, 442, 3) 

 imshow()用以显示图片,destroAllWindows()销毁图片显示窗口

 waitKey(5000)程序在此处等待5000ms再执行下一条语句(0表示任意时间)或者按下键盘就会执行下一条语句  

img2 = cv2.resize(img, (150, 150), interpolation=cv2.INTER_CUBIC)
img3 = cv2.resize(img, None, fx=1/2, fy=1/2, interpolation=cv2.INTER_AREA)

 绝对的和相对的resize方式,interpolation可取 cv2.INTER_AREA(适合缩小)、cv2.INTER_CUBIC(适合放大)和 cv2.INTER_LINEAR(默认)

M = numpy.float32([[1, 0, 100], [0, 1, 50]])    # x轴平移100 y轴平移50
img1 = cv2.warpAffine(img, M, (width, height)) # 显示图片大小 黑色填充
# M = cv2.getRotationMatrix2D((442/2, 600/2), 90, 1)    #三个参数表示: 旋转中心 逆时针选择角度 缩放比例
# img1 = cv2.warpAffine(img, M, (img.shape[1], img.shape[0])) 

 颜色变换: img1=cv2.cvtColor(img ,flag) 图片打开时都是BGR格式 ,flag为转换类型,如cv2.COLOR_BGR2RGB、cv2.COLOR_BGR2GRAY

灰度图二值化: ret,img1 = cv2.threshold(img_gray,175,255,cv2.THRESH_BINARY) 小于阈值175的置为0,否则置为1.

 最后一个参数可以是 THRESH_BINARY=0、THRESH_BINARY_INV、THRESH_TRUNC、THRESH_TOZERO、THRESH_TOZERO_INV

仿射变换:  (详细点此)

import cv2
import numpy

img = cv2.imread('alison.jpg',1)

pts1 = numpy.float32([[50, 50], [200, 50], [50, 200]])
pts2 = numpy.float32([[10, 100], [200, 50], [100, 250]])
M = cv2.getAffineTransform(pts1,pts2)
img1 = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))

cv2.imshow('alison1',img1)
cv2.waitKey(0) 

 

参考:

 cv2库处理验证码https://www.cnblogs.com/lizm166/p/9969647.html

 cv2库常见使用方法https://blog.csdn.net/Canon__/article/details/83247687

 skimage库连通域去噪http://www.cppcns.com/jiaoben/python/226532.html

 2020-05-27 22:09:14

posted @ 2020-05-27 22:09  shines87  阅读(401)  评论(0)    收藏  举报