demo_ocr.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- codeing = utf-8 -*-
  2. # @Time : 2024/3/6 19:02
  3. # @Author : Clown
  4. # @File : demo_ocr.py
  5. # @Software : PyCharm
  6. import cv2
  7. import pytesseract
  8. import numpy as np
  9. from PIL import Image
  10. import pandas as pd
  11. path_in = r'C:\Users\ClownHe\Desktop\1业务支持需求单\Screenshot_2024-03-06-12-10-09-94_e39d2c7de19156b0683cd93e8735f348(1).jpg'
  12. # 加载图像
  13. image = Image.open(path_in)
  14. image = np.array(image)
  15. # 图像预处理(灰度化)
  16. gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  17. # 文字识别
  18. '''
  19. psm值为3表示全自动页面分割模式(默认值)。
  20. psm值为6表示假设文本是单个统一的块。
  21. psm值为7表示将图像视为一个单一的文本行。
  22. psm值为8表示将图像视为一个包含多个文本行的块。
  23. '''
  24. boxes = pytesseract.image_to_boxes(gray_image,lang = 'chi_sim+eng',config = '--psm 6',output_type = pytesseract.Output.STRING)
  25. '''
  26. <char>:识别出的字符。
  27. <left>:字符在图像中的左边界距离图像左侧的距离。
  28. <top>:字符在图像中的上边界距离图像顶部的距离。
  29. <width>:字符的宽度。
  30. <height>:字符的高度。
  31. <conf>:模型对字符属于该类别的置信度,通常是一个介于0和1之间的值
  32. '''
  33. datas = pytesseract.image_to_data(gray_image,lang = 'chi_sim+eng',config = '--psm 6',output_type=pytesseract.Output.DICT)
  34. '''
  35. level:字符的级别,表示该字符在文本中的重要性。
  36. page_num:字符所在的页面编号。
  37. block_num:字符所在的块编号。
  38. par_num:字符所在的段落编号。
  39. line_num:字符所在的行号。
  40. word_num:字符所在的单词编号。
  41. left:字符左边界距离图像左侧的距离。
  42. top:字符上边界距离图像顶部的距离。
  43. width:字符的宽度。
  44. height:字符的高度。
  45. conf:字符的置信度评分,表示识别结果的准确性。
  46. text:识别出的字符本身。
  47. '''
  48. df_out = pd.DataFrame(datas).to_dict('records')
  49. for row in df_out:
  50. if row['conf'] in range(88,100) and row['text'] == ' ':
  51. print(row)
  52. x, y, w, h = int(row['left']), int(row['top']), int(row['width']), int(row['height'])
  53. cv2.rectangle(image, (x, y), (w+x, h+y), (0, 255, 0), 2)
  54. # 绘制文本框
  55. for box in boxes.splitlines():
  56. print(box,type(box))
  57. # coordinates = box.split()
  58. #
  59. # x, y, w, h = int(coordinates[1]), int(coordinates[2]), int(coordinates[3]), int(coordinates[4])
  60. # cv2.rectangle(image, (x, image.shape[0] - y), (w, image.shape[0] - h), (0, 255, 0), 2)
  61. # 缩放图像
  62. scale_percent = 50 # 缩放比例(百分比)
  63. width = int(image.shape[1] * scale_percent / 100)
  64. height = int(image.shape[0] * scale_percent / 100)
  65. dim = (width, height)
  66. resized_image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
  67. # 显示结果
  68. cv2.imshow('Result', resized_image)
  69. cv2.waitKey(0)
  70. cv2.destroyAllWindows()