main.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import cv2
  2. import numpy as np
  3. cap = cv2.VideoCapture(0)
  4. while True:
  5. img = cap.read()[1]
  6. orig = img.copy()
  7. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  8. blur = cv2.GaussianBlur(gray, (5, 5), 0)
  9. _, thres = cv2.threshold(blur, 200, 255, cv2.THRESH_BINARY)
  10. cts, _ = cv2.findContours(thres, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  11. contour = max(cts, key=cv2.contourArea)
  12. epsilon = 0.02 * cv2.arcLength(contour, True)
  13. approx = cv2.approxPolyDP(contour, epsilon, True)
  14. if len(approx) == 4:
  15. pts = approx.reshape(4, 2)
  16. rect = np.zeros((4, 2), dtype="float32")
  17. s = pts.sum(axis=1)
  18. rect[0] = pts[np.argmin(s)]
  19. rect[2] = pts[np.argmax(s)]
  20. diff = np.diff(pts, axis=1)
  21. rect[1] = pts[np.argmin(diff)]
  22. rect[3] = pts[np.argmax(diff)]
  23. (tl, tr, br, bl) = rect
  24. widthA = np.linalg.norm(br - bl)
  25. widthB = np.linalg.norm(tr - tl)
  26. maxWidth = max(int(widthA), int(widthB))
  27. heightA = np.linalg.norm(tr - br)
  28. heightB = np.linalg.norm(tl - bl)
  29. maxHeight = max(int(heightA), int(heightB))
  30. dst = np.array(
  31. [
  32. [0, 0],
  33. [maxWidth - 1, 0],
  34. [maxWidth - 1, maxHeight - 1],
  35. [0, maxHeight - 1],
  36. ],
  37. dtype="float32",
  38. )
  39. M = cv2.getPerspectiveTransform(rect, dst)
  40. warped = cv2.warpPerspective(orig, M, (maxWidth, maxHeight))
  41. cv2.putText(
  42. warped,
  43. "llpoDaM rapa>|<",
  44. (0, 50),
  45. cv2.FONT_HERSHEY_SIMPLEX,
  46. 1,
  47. (0, 0, 0),
  48. 2,
  49. )
  50. M_inv = cv2.getPerspectiveTransform(dst, rect)
  51. warped_back = cv2.warpPerspective(warped, M_inv, (orig.shape[1], orig.shape[0]))
  52. mask = np.zeros_like(gray)
  53. cv2.fillConvexPoly(mask, approx, 255)
  54. masked = cv2.bitwise_and(orig, orig, mask=cv2.bitwise_not(mask))
  55. final = cv2.add(masked, warped_back)
  56. cv2.imshow("img", final)
  57. cv2.waitKey(1)
  58. else:
  59. cv2.imshow("img", orig)
  60. cv2.waitKey(1)