# Python识别验证码！学会这步，百分之60的网站你基本都能识别了！

127是我们设定的阈值，像素值大于127被置成了0，小于127的被置成了255。处理后的图片变成了这样

kernel = 1/16*np.array([[1,2,1], [2,4,2], [1,2,1]])

im_blur = cv2.filter2D(im_inv,-1,kernel)

ret, im_res = cv2.threshold(im_blur,127,255,cv2.THRESH_BINARY)

im2, contours, hierarchy = cv2.findContours(im_res, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

4个字符被识别成3个字符

result = []

for contour in contours:

x, y, w, h = cv2.boundingRect(contour)

if w == w_max: # w_max是所有contonur的宽度中最宽的值

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)

4个字符被识别成2个字符

4个字符被识别成2个字符有下面两种情况

result = []

for contour in contours:

x, y, w, h = cv2.boundingRect(contour)

if w == w_max and w_max >= w_min * 2:

# 如果两个轮廓一个是另一个的宽度的2倍以上，我们认为这个轮廓就是包含3个字符的轮廓

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:

# 如果两个轮廓，较宽的宽度小于较窄的2倍，我们认为这是两个包含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)

4个字符被识别成1个字符

result = []

contour = 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])

for box in result:

cv2.drawContours(im, [box], 0, (0,0,255),2)

roi = im_res[box[0][1]:box[3][1], box[0][0]:box[1][0]]

roistd = cv2.resize(roi, (30, 30)) # 将字符图片统一调整为30x30的图片大小

timestamp = int(time.time() * 1e6) # 为防止文件重名，使用时间戳命名文件名

filename = "{}.jpg".format(timestamp)

filepath = os.path.join("char", filename)

cv2.imwrite(filepath, roistd)

files = os.listdir("char")

for filename in files:

filename_ts = filename.split(".")[0]

patt = "label/{}_*".format(filename_ts)

saved_num = len(glob.glob(patt))

if saved_num == 1:

print("{} done".format(patt))

continue

filepath = os.path.join("char", filename)

cv2.imshow("image", im)

key = cv2.waitKey(0)

if key == 27:

sys.exit()

if key == 13:

continue

char = chr(key)

filename_ts = filename.split(".")[0]

outfile = "{}_{}.jpg".format(filename_ts, char)

outpath = os.path.join("label", outfile)

cv2.imwrite(outpath, im)

filenames = os.listdir("label")

samples = np.empty((0, 900))

labels = []

for filename in filenames:

filepath = os.path.join("label", filename)

label = filename.split(".")[0].split("_")[-1]

labels.append(label)

sample = im.reshape((1, 900)).astype(np.float32)

samples = np.append(samples, sample, 0)

samples = samples.astype(np.float32)

unique_labels = list(set(labels))

unique_ids = list(range(len(unique_labels)))

label_id_map = dict(zip(unique_labels, unique_ids))

id_label_map = dict(zip(unique_ids, unique_labels))

label_ids = list(map(lambda x: label_id_map[x], labels))

label_ids = np.array(label_ids).reshape((-1, 1)).astype(np.float32)

model = cv2.ml.KNearest_create()

model.train(samples, cv2.ml.ROW_SAMPLE, label_ids)

for box in boxes:

roi = im_res[box[0][1]:box[3][1], box[0][0]:box[1][0]]

roistd = cv2.resize(roi, (30, 30))

sample = roistd.reshape((1, 900)).astype(np.float32)

ret, results, neighbours, distances = model.findNearest(sample, k = 3)

label_id = int(results[0,0])

label = id_label_map[label_id]

print(label)

y

y

4

e

133 篇文章27 人订阅

0 条评论

## 相关文章

2274

1.3K7

4097

1395

1936

1337

3246

1152

3195

### 【TensorFlow】理解 Estimators 和 Datasets

Google 在 2017 年 9 月 12 号的博文 Introduction to TensorFlow Datasets and Estimators 中...

1.3K8