correct-2.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import cv2
  2. import numpy as np
  3. def deskew_image(image_array):
  4. # 转换为灰度图像
  5. gray = cv2.cvtColor(image_array, cv2.COLOR_BGR2GRAY)
  6. # 使用边缘检测找到倾斜角度
  7. edges = cv2.Canny(gray, 150, 255, apertureSize=3)
  8. cv2.imshow("edges", edges)
  9. lines = cv2.HoughLines(edges, 1, np.pi / 180, 200)
  10. print(lines.shape)
  11. print(lines)
  12. theta = lines[0][0][1] if lines is not None else 0
  13. # 旋转图像以校正倾斜
  14. (h, w) = image_array.shape[:2]
  15. center = (w // 2, h // 2)
  16. M = cv2.getRotationMatrix2D(center, np.degrees(theta), 1.0)
  17. rotated = cv2.warpAffine(image_array, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
  18. # 裁剪校正后的图像
  19. gray = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)
  20. _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
  21. coords = np.column_stack(np.where(thresh > 0))
  22. angle = cv2.minAreaRect(coords)[-1]
  23. if angle < -45:
  24. angle = -(90 + angle)
  25. else:
  26. angle = -angle
  27. (h, w) = rotated.shape[:2]
  28. center = (w // 2, h // 2)
  29. M = cv2.getRotationMatrix2D(center, angle, 1.0)
  30. rotated = cv2.warpAffine(rotated, M, (w, h), flags=cv2.INTER_CUBIC, borderMode=cv2.BORDER_REPLICATE)
  31. # 校准透视变换
  32. gray = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)
  33. thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  34. contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  35. cnt = contours[0]
  36. rect = cv2.minAreaRect(cnt)
  37. box = cv2.boxPoints(rect)
  38. box = np.intp(box)
  39. width = int(rect[1][0])
  40. height = int(rect[1][1])
  41. src_pts = box.astype("float32")
  42. dst_pts = np.array([[0, height - 1],
  43. [0, 0],
  44. [width - 1, 0],
  45. [width - 1, height - 1]], dtype="float32")
  46. M = cv2.getPerspectiveTransform(src_pts, dst_pts)
  47. warped = cv2.warpPerspective(rotated, M, (width, height))
  48. return warped
  49. def main():
  50. # 示例用法
  51. path = "img/18.jpg"
  52. img = cv2.imread(path)
  53. corrected_array = deskew_image(img)
  54. cv2.imshow("name", corrected_array)
  55. cv2.waitKey(0)
  56. if __name__ == '__main__':
  57. main()