因朋友请求,帮忙写了个CV的验证码提取,由于他的验证码中间噪音不是很高,所以各种滤波的降噪在代码中没有,所以想看降噪的朋友可能要失望了,话不多说,附上源码
import cv2
import numpy as np
height = 180
width = 600
threshold = 130 # 阈值
def threshold_demo(image):
for i in range(height):
for j in range(width):
if image[i][j] > threshold:
image[i][j] = 255
else:
image[i][j] = 0
return image
def split_picture(imagepath):
img = cv2.imread(imagepath)
img = cv2.resize(img, (width, height))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 将图片的边缘变为白色
# for i in range(width):
# gray[0, i] = 255
# gray[height-1, i] = 255
# for j in range(height):
# gray[j, 0] = 255
# gray[j, width-1] = 255
thresh1 = threshold_demo(gray)
contours, hierarchy = cv2.findContours(thresh1, 2, 2)
for i in range(len(contours)):
cnt = contours[i]
# 寻找每个轮廓的最小外接矩形
x, y, w, h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
if w > 0.8*width or h > 0.8 * height:
continue
if w < width*0.083 or h < height*0.25:
continue
print((x, y, w, h))
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.drawContours(img, contours, i, (0, 255, 0), 2)
cv2.imshow('img', img)
cv2.imshow('gray', gray)
cv2.imshow('thresh1', thresh1)
cv2.waitKey(0)
if __name__ == '__main__':
imagepath = '你的图片路径'
split_picture(imagepath)
原图:
下面是测试效果: