opencv处理验证码python代码

# -*- coding: utf-8 -*-
# @Time : 2019-02-11 09:39
# @Author : cxa
# @File : bgr2gry.py
# @Software: PyCharm
import cv2
import pathlib
import numpy as np
import time
import os

file_path = pathlib.Path.cwd().joinpath("picture/1.png")
char_path = pathlib.Path.cwd().joinpath("char_path")


def get_rect_box(contours):
    ws = []
    valid_contours = []
    for contour in contours:
        x, y, w, h = cv2.boundingRect(contour)
        if w < 7:
            continue
        valid_contours.append(contour)
        ws.append(w)

    w_min = min(ws)
    w_max = max(ws)

    result = []
    if len(valid_contours) == 4:
        for contour in valid_contours:
            x, y, w, h = cv2.boundingRect(contour)
            box = np.int0([[x, y], [x + w, y], [x + w, y + h], [x, y + h]])
            result.append(box)
    elif len(valid_contours) == 3:
        for contour in valid_contours:
            x, y, w, h = cv2.boundingRect(contour)
            if w == w_max:
                box_left = np.int0([[x, y], [x + w / 2, y], [x + w / 2, y + h], [x, y + h]])
                box_right = np.int0([[x + w / 2, y], [x + w, y], [x + w, y + h], [x + w / 2, y + h]])
                result.append(box_left)
                result.append(box_right)
            else:
                box = np.int0([[x, y], [x + w, y], [x + w, y + h], [x, y + h]])
                result.append(box)
    elif len(valid_contours) == 2:
        for contour in valid_contours:
            x, y, w, h = cv2.boundingRect(contour)
            if w == w_max and w_max >= w_min * 2:
                box_left = np.int0([[x, y], [x + w / 3, y], [x + w / 3, y + h], [x, y + h]])
                box_mid = np.int0([[x + w / 3, y], [x + w * 2 / 3, y], [x + w * 2 / 3, y + h], [x + w / 3, y + h]])
                box_right = np.int0([[x + w * 2 / 3, y], [x + w, y], [x + w, y + h], [x + w * 2 / 3, y + h]])
                result.append(box_left)
                result.append(box_mid)
                result.append(box_right)
            elif w_max < w_min * 2:
                box_left = np.int0([[x, y], [x + w / 2, y], [x + w / 2, y + h], [x, y + h]])
                box_right = np.int0([[x + w / 2, y], [x + w, y], [x + w, y + h], [x + w / 2, y + h]])
                result.append(box_left)
                result.append(box_right)
            else:
                box = np.int0([[x, y], [x + w, y], [x + w, y + h], [x, y + h]])
                result.append(box)
    elif len(valid_contours) == 1:
        contour = valid_contours[0]
        x, y, w, h = cv2.boundingRect(contour)
        box0 = np.int0([[x, y], [x + w / 4, y], [x + w / 4, y + h], [x, y + h]])
        box1 = np.int0([[x + w / 4, y], [x + w * 2 / 4, y], [x + w * 2 / 4, y + h], [x + w / 4, y + h]])
        box2 = np.int0([[x + w * 2 / 4, y], [x + w * 3 / 4, y], [x + w * 3 / 4, y + h], [x + w * 2 / 4, y + h]])
        box3 = np.int0([[x + w * 3 / 4, y], [x + w, y], [x + w, y + h], [x + w * 3 / 4, y + h]])
        result.extend([box0, box1, box2, box3])
    elif len(valid_contours) > 4:
        for contour in valid_contours:
            x, y, w, h = cv2.boundingRect(contour)
            box = np.int0([[x, y], [x + w, y], [x + w, y + h], [x, y + h]])
            result.append(box)
    result = sorted(result, key=lambda x: x[0][0])
    return result


# 干扰线降噪
def interference_line(img, img_name):
    h, w = img.shape[:2]
    # !!!opencv矩阵点是反的
    # img[1,2] 1:图片的高度,2:图片的宽度
    for y in range(1, w - 1):
        for x in range(1, h - 1):
            count = 0
            if img[x, y - 1] > 245:
                count = count + 1
            if img[x, y + 1] > 245:
                count = count + 1
            if img[x - 1, y] > 245:
                count = count + 1
            if img[x + 1, y] > 245:
                count = count + 1
            if count > 2:
                img[x, y] = 255
    cv2.imwrite(str(img_name), img)
    return img


im = cv2.imread(str(file_path))
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)  # 将图片转成灰度图
# 将图片做二值化处理
ret, im_inv = cv2.threshold(im_gray, 127, 255, cv2.THRESH_BINARY_INV)
# 高斯模糊对图片进行降噪
kernel = 1 / 16 * np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]])
im_blur = cv2.filter2D(im_inv, -1, kernel)

# 再做一轮二值化处理
ret, binary = cv2.threshold(im_blur, 127, 255, cv2.THRESH_BINARY)
f_path2 = pathlib.Path.cwd().joinpath("picture/2.png")

# 去干扰线
last_im = interference_line(binary, f_path2)

# 识别

# 切割图片
# contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# boxes=get_rect_box(contours)
# for box in boxes:
#         cv2.drawContours(im, [box], 0, (0,0,255),2)
#         roi = binary[box[0][1]:box[3][1], box[0][0]:box[1][0]]
#         roistd = cv2.resize(roi, (30, 30))
#         timestamp = int(time.time() * 1e6)
#         filename = "{}.jpg".format(timestamp)
#         filepath = os.path.join(char_path, filename)
#         cv2.imwrite(filepath, roistd)
# cv2.drawContours(im, contours, -1, (0, 0, 255), 3)
# cv2.imshow('IMG', im)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

posted @ 2019-02-22 16:34  公众号python学习开发  阅读(813)  评论(0编辑  收藏  举报