14.基于opencv实现文字识别

本是古典 何须时尚 2024-04-07 12:24 193阅读 0赞
  1. from typing import Tuple
  2. import cv2
  3. import numpy as np
  4. def grayScale(img : np.ndarray) -> np.ndarray:
  5. return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  6. def blur(img : np.ndarray, k: int = 3, std : int = 0) -> np.ndarray:
  7. return cv2.GaussianBlur(img, (k,k), std)
  8. def binary(img : np.ndarray) -> np.ndarray:
  9. return cv2.Canny(img, 100, 255)
  10. def retBiggestContour(img : np.ndarray) -> Tuple[np.ndarray, Tuple[int, int]]:
  11. contours, _ = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
  12. cnt = sorted(contours, key = cv2.contourArea)[-1]
  13. _, (w,h), angle = cv2.minAreaRect(cnt)
  14. w,h = int(w), int(h)
  15. if angle > 45 or angle < -45:
  16. w,h = h,w
  17. return cnt, (w,h)
  18. def extract(img : np.ndarray,
  19. cnt : np.ndarray,
  20. w : int,
  21. h : int
  22. ) -> np.ndarray:
  23. cnt = cnt.reshape(cnt.shape[0], cnt.shape[-1])
  24. # the corners have extreme x, y coordinates
  25. s1 = sorted(cnt, key = lambda x : (x[0], x[1]))
  26. s2 = sorted(cnt, key = lambda x : (x[1], x[0]))
  27. corner1, corner3 = s1[0], s1[-1]
  28. corner2, corner4 = s2[0], s2[-1]
  29. corners = np.array([corner1, corner2, corner3, corner4])
  30. target_corners = np.array([(0,0), (w,0), (w,h), (0,h)])
  31. H, _ = cv2.findHomography(corners, target_corners, params = None)
  32. transformed_image = cv2.warpPerspective(
  33. img, H, (img.shape[1], img.shape[0]))
  34. transformed_image = transformed_image[:h, :w]
  35. return transformed_image
  36. def transform(img : np.ndarray) -> np.ndarray:
  37. T = cv2.GaussianBlur(img, (11,11),0)-10
  38. return (img > T).astype(np.uint8) * 255
  39. if __name__ == "__main__":
  40. img = cv2.imread("G:/py/i/wenzi.jpg")
  41. gray = grayScale(img)
  42. blurred = blur(gray)
  43. edged = binary(blurred)
  44. cnt, (w,h) = retBiggestContour(edged)
  45. img = extract(gray, cnt, w, h)
  46. img = transform(img)
  47. cv2.namedWindow('img',cv2.WINDOW_NORMAL)
  48. cv2.imshow('img',img)
  49. k = cv2.waitKey(0)&0xFF
  50. if k == 27:
  51. cv2.destroyAllWindows()
  52. elif k == ord('q'):
  53. cv2.destroyAllWindows()
  54. #cv2.imwrite("G:/transformed.jpg", img)

发表评论

表情:
评论列表 (有 0 条评论,193人围观)

还没有评论,来说两句吧...

相关阅读

    相关 基于OpenCV快速实现人脸识别

    以后打算多多关注计算机视觉这一块,涉猎广一些,对今后的毕设也有益处。 做一下人脸识别吧,之前看到一个博主写的一个demo,错误不少,经过修改以及查询资料,现在整理一下思路。

    相关 OpenCV可以识别文字吗?

    仅OpenCV而言并不能。你的问题类似于土豆可以用来吃饭吗。OpenCV是一个开源的计算机视觉库,而OCR 是一个工程、一个解决方案,OCR可以用OpenCV,也可以不用,理论