1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
import cv2 as cv
def get_pos(image): blurred = cv.GaussianBlur(image, (5, 5), 0) canny = cv.Canny(blurred, 200, 400) binary, contours, hierarchy = cv.findContours(canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) for i, contour in enumerate(contours): M = cv.moments(contour) if M['m00'] == 0: cx = cy = 0 else: cx, cy = M['m10'] / M['m00'], M['m01'] / M['m00'] ''' 笔者是根据打印日志 来算出自己验证码的周长和大小 方法是先把所有的轮廓画出来 然后根据实际坐标 反推 print("start") print(x, y, w, h) print(cx) print(cv.contourArea(contour)) print(cv.arcLength(contour, True)) print("end") ''' if (25 < cv.contourArea(contour) < 30 and 400 < cv.arcLength(contour, True) < 450): if cx < 125: continue x, y, w, h = cv.boundingRect(contour) cv.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) cv.imshow('image', image) return x return 0
if __name__ == '__main__': img0 = cv.imread('slide.png') get_pos(img0) cv.waitKey(0) cv.destroyAllWindows()
|