|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +def getContours(img,cThr=[100,100],showCanny=False,minArea=1000,filter=0,draw =False): |
| 5 | + imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) |
| 6 | + imgBlur = cv2.GaussianBlur(imgGray,(5,5),1) |
| 7 | + imgCanny = cv2.Canny(imgBlur,cThr[0],cThr[1]) |
| 8 | + kernel = np.ones((5,5)) |
| 9 | + imgDial = cv2.dilate(imgCanny,kernel,iterations=3) |
| 10 | + imgThre = cv2.erode(imgDial,kernel,iterations=2) |
| 11 | + if showCanny:cv2.imshow('Canny',imgThre) |
| 12 | + contours,hiearchy = cv2.findContours(imgThre,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) |
| 13 | + finalCountours = [] |
| 14 | + for i in contours: |
| 15 | + area = cv2.contourArea(i) |
| 16 | + if area > minArea: |
| 17 | + peri = cv2.arcLength(i,True) |
| 18 | + approx = cv2.approxPolyDP(i,0.02*peri,True) |
| 19 | + bbox = cv2.boundingRect(approx) |
| 20 | + if filter > 0: |
| 21 | + if len(approx) == filter: |
| 22 | + finalCountours.append([len(approx),area,approx,bbox,i]) |
| 23 | + else: |
| 24 | + finalCountours.append([len(approx),area,approx,bbox,i]) |
| 25 | + finalCountours = sorted(finalCountours,key = lambda x:x[1] ,reverse= True) |
| 26 | + if draw: |
| 27 | + for con in finalCountours: |
| 28 | + cv2.drawContours(img,con[4],-1,(0,0,255),3) |
| 29 | + return img, finalCountours |
| 30 | + |
| 31 | +def reorder(myPoints): |
| 32 | + #print(myPoints.shape) |
| 33 | + myPointsNew = np.zeros_like(myPoints) |
| 34 | + myPoints = myPoints.reshape((4,2)) |
| 35 | + add = myPoints.sum(1) |
| 36 | + myPointsNew[0] = myPoints[np.argmin(add)] |
| 37 | + myPointsNew[3] = myPoints[np.argmax(add)] |
| 38 | + diff = np.diff(myPoints,axis=1) |
| 39 | + myPointsNew[1]= myPoints[np.argmin(diff)] |
| 40 | + myPointsNew[2] = myPoints[np.argmax(diff)] |
| 41 | + return myPointsNew |
| 42 | + |
| 43 | +def warpImg (img,points,w,h,pad=20): |
| 44 | + # print(points) |
| 45 | + points =reorder(points) |
| 46 | + pts1 = np.float32(points) |
| 47 | + pts2 = np.float32([[0,0],[w,0],[0,h],[w,h]]) |
| 48 | + matrix = cv2.getPerspectiveTransform(pts1,pts2) |
| 49 | + imgWarp = cv2.warpPerspective(img,matrix,(w,h)) |
| 50 | + imgWarp = imgWarp[pad:imgWarp.shape[0]-pad,pad:imgWarp.shape[1]-pad] |
| 51 | + return imgWarp |
| 52 | + |
| 53 | +def findDis(pts1,pts2): |
| 54 | + return ((pts2[0]-pts1[0])**2 + (pts2[1]-pts1[1])**2)**0.5 |
| 55 | + |
| 56 | + |
0 commit comments