近日某眾打碼平台被跑路的消息一出,腳本圈中一片嘩然(我並不是腳本圈的,只是喜歡看群裡人吹逼而已 ),仿佛再也聽不到那句熟悉的廣告語了.這也預示著,第三方打碼平台不靠譜了.但打碼功能有時候又必不可少,這時候怎麼辦呢?當然是自己自己動手豐衣足食啦!最近工作不是很忙,准備撸一個用Python識別驗證碼的系列文章,該系列計劃囊括各種時下比較流行的驗證碼形式,如滑塊、四則運算、點選、手勢、空間推理、谷歌等.已經跑通了的所有代碼都放在了我的知識星球上,需要的話請自取.話不多說,開撸!
Lets you pick the area with the largest area,不得不說,The verification code is really getting more and more volume,more and more spent.
However, this verification code seems to have not many pictures,There seem to be just a few backgrounds,That is, those lines will change back and forth,And the color of the line is quite different from the background.So the general idea is to find a way to separate the line from the background,Then do contour detection,Find the contour with the largest area and calculate the centroid of the contourojbk了.
1.The lines are all brighter in color,So here the graph is converted to HSV顏色空間,and separatelyVChannel out for use
原圖:
V通道圖:
2.Do a gamma transform,Make brighter places brighter,Make darker places darker.
adjusted = gamma_trans(v_img, 9.3)
3.Because some of the points that belong to the line may be dim,So I thought of a way,Multiply all pixels by a larger number,Add a certain value.這樣的話,The darker spots on the line also become brighter.
adjusted = cv2.convertScaleAbs(adjusted, alpha=13, beta=20)
4.At this point, most of the points on the line are close to white,At this time, there is a wave of thresholding.
_, adjusted = cv2.threshold(adjusted, 200, 255, cv2.THRESH_BINARY)
5.There are gaps between the line segments,You need to fill them with white to calculate the outline,So swell it up.Here, in order to fill in the pores as much as possible,So the core is bigger.
kernel = np.ones([12, 12], dtype=np.uint8)
adjusted = cv2.dilate(adjusted, kernel, iterations=2)
6.opposite phase,Because contour detection detects white areas by default,But what we need is the outline of the black area.
adjusted = np.ones([adjusted.shape[0], adjusted.shape[1]], dtype=np.uint8) * 255 - adjusted
7.輪廓檢測,Picks the largest contour out of many contours.
8.The coordinates of the center point of the contour can be calculated by calculating the first moment of the largest contour.
M = cv2.moments(contours[max_contour_index])
center_x = int(M["m10"] / M["m00"])
center_y = int(M["m01"] / M["m00"])
大概測試了20幾次,對了19次.It is estimated that the gallery of this verification code itself is not large,So this is enough.
If you want to generalize more powerfully,It is still recommended to collect some more graphs and use some network graphs to generate some similar graphs,Then train a segmentation model to do the segmentation.After all, if the picture of the verification code changes,Then this pure image processing method may not be applicable.