Advertisement
Guest User

Untitled

a guest
Dec 19th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.79 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. from pytesseract import pytesseract
  4. from operator import itemgetter
  5.  
  6. pytesseract.tesseract_cmd = r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"
  7. img = cv2.imread('static/im11.png')
  8. img = cv2.resize(img, (850,350))
  9. img2 = img
  10. # threshold image
  11. ret, threshed_img = cv2.threshold(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY),
  12. 130, 255, cv2.THRESH_BINARY)
  13. # find contours and get the external one
  14. image, contours, hierarchy = cv2.findContours(threshed_img, cv2.RETR_TREE,
  15. cv2.CHAIN_APPROX_SIMPLE)
  16.  
  17. boxes = list()
  18. cropped_imageList = list()
  19. plate = list()
  20. #получаем координаты прямоугольников вокруг контуров
  21. for c in contours:
  22. x, y, w, h = cv2.boundingRect(c)
  23. boxes.append((x,y,w,h)) #хранит координаты каждого прямоугольника
  24.  
  25. boxesBasic = [i for i in boxes if (49 < i[3] < 250) and i[0] > 60 and (i[2]/i[3] < 0.8)]#убираем слишком высокие и слишком низкие контуры
  26. boxesBasic.sort(key=itemgetter(0))
  27.  
  28. boxesBasic = sorted(boxesBasic)
  29. #убираем контуры внутри контуров
  30. for x in boxesBasic:
  31. for y in boxesBasic:
  32. if x[0] < y[0] and x[1] < y[1] and (x[1] + x[3]) > (y[1] + y[3]) and (x[0] + x[2]) > (y[0] + y[2]):
  33. boxesBasic.remove(y)
  34.  
  35. #что-то в блоке выше работает не так, это для надежности
  36. boxesInner = [i for i in boxesBasic if not( 180 < i[0] and i[3] < 150) or not (i[0] < 370 and i[3] < 150)]
  37.  
  38. #так как контуры выводятся в порядке возрастания координаты Х получается что-то типа а008мрr1u9s9
  39. #нужно поменять местами цифры номера и буквы названия региона
  40. if len(boxesInner) == 12:
  41. boxesInner[7],boxesInner[9]=boxesInner[9],boxesInner[7]
  42. boxesInner[8],boxesInner[11],=boxesInner[11],boxesInner[8]
  43. boxesInner[10],boxesInner[11]=boxesInner[11],boxesInner[10]
  44. else:
  45. boxesInner[6],boxesInner[7]=boxesInner[7],boxesInner[6]
  46. boxesInner[9], boxesInner[10] = boxesInner[10], boxesInner[9]
  47. boxesInner[8], boxesInner[9] = boxesInner[9], boxesInner[8]
  48. boxesInner[7], boxesInner[8] = boxesInner[8], boxesInner[7]
  49.  
  50. #вырезание прямоугольников (и их отрисовка заодно)
  51. for each in boxesInner:
  52. x = each[0]
  53. y = each[1]
  54. w = each[2]
  55. h = each[3]
  56. #рисует прямоугольники (изобр, координаты, цвет, толщина контура)
  57. #cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 3)
  58. crop_img = img[y:y+h, x:x+w]#вырезает прямоугольник с контуром
  59. crop_img = cv2.resize(crop_img,(150,300))#увеличивает в размере (ТЕССЕРАКТ ТРЕБОВАТЕЛЕН К РАЗМЕРУ, НЕ МЕНЬШЕ 300 ПИКСЕЛЕЙ ПО ВЕРТИКАЛИ)
  60. cropped_imageList.append(crop_img)
  61.  
  62. #БУКОВКА В НАЧАЛЕ
  63. config1 = ("-l platechar --psm 10 --oem 3")
  64. x = cropped_imageList[0]
  65. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  66. 127, 255, cv2.THRESH_BINARY)
  67. text = pytesseract.image_to_string(threshed_x, config=config1)
  68.  
  69. plate.append(text)
  70.  
  71. #ЦИФЕРКИ В СЕРЕДИНЕ
  72. config1 = ("-l platenum --psm 10")
  73. x = cropped_imageList[1]
  74. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  75. 127, 255, cv2.THRESH_BINARY)
  76. text = pytesseract.image_to_string(threshed_x, config=config1)
  77. text = pytesseract.image_to_string(x, config=config1)
  78. plate.append(text)
  79.  
  80. config1 = ("-l platenum --psm 10")
  81. x = cropped_imageList[2]
  82. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  83. 127, 255, cv2.THRESH_BINARY)
  84. text = pytesseract.image_to_string(threshed_x, config=config1)
  85. text = pytesseract.image_to_string(x, config=config1)
  86. plate.append(text)
  87.  
  88. config1 = ("-l platenum --psm 10")
  89. x = cropped_imageList[3]
  90. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  91. 127, 255, cv2.THRESH_BINARY)
  92. text = pytesseract.image_to_string(threshed_x, config=config1)
  93. text = pytesseract.image_to_string(x, config=config1)
  94. plate.append(text)
  95. #КОНЕЦ ЦИФЕРОК В СЕРЕДИНЕ
  96.  
  97. #БУКОВКИ ПЕРЕД РЕГИОНОМ
  98. config1 = ("-l platechar --psm 10 --oem 3")
  99. x = cropped_imageList[4]
  100. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  101. 127, 255, cv2.THRESH_BINARY)
  102. text = pytesseract.image_to_string(threshed_x, config=config1)
  103. plate.append(text)
  104.  
  105. config1 = ("-l platechar --psm 10 --oem 3")
  106. x = cropped_imageList[5]
  107. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  108. 127, 255, cv2.THRESH_BINARY)
  109. text = pytesseract.image_to_string(threshed_x, config=config1)
  110. plate.append(text)
  111. #КОНЕЦ БУКОВОК ПЕРЕД РЕГИОНОМ
  112.  
  113. #если регион двузначный
  114. if len(boxesInner) == 11:
  115. #ЦИФРЫ
  116. config1 = ("-l platenum --psm 10")
  117. x = cropped_imageList[6]
  118. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  119. 127, 255, cv2.THRESH_BINARY)
  120. text = pytesseract.image_to_string(threshed_x, config=config1)
  121. text = pytesseract.image_to_string(x, config=config1)
  122. plate.append(text)
  123.  
  124. config1 = ("-l platenum --psm 10")
  125. x = cropped_imageList[7]
  126. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  127. 127, 255, cv2.THRESH_BINARY)
  128. text = pytesseract.image_to_string(threshed_x, config=config1)
  129. text = pytesseract.image_to_string(x, config=config1)
  130. plate.append(text)
  131.  
  132. text = 'R'
  133. plate.append(text)
  134. text = 'U'
  135. plate.append(text)
  136. text = 'S'
  137. plate.append(text)
  138.  
  139. #если регион трехзначный
  140. if len(boxesInner) == 12:
  141. config1 = ("-l platenum --psm 10")
  142. x = cropped_imageList[6]
  143. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  144. 127, 255, cv2.THRESH_BINARY)
  145. text = pytesseract.image_to_string(threshed_x, config=config1)
  146. text = pytesseract.image_to_string(x, config=config1)
  147. plate.append(text)
  148.  
  149. config1 = ("-l platenum --psm 10")
  150. x = cropped_imageList[7]
  151. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  152. 127, 255, cv2.THRESH_BINARY)
  153. text = pytesseract.image_to_string(threshed_x, config=config1)
  154. text = pytesseract.image_to_string(x, config=config1)
  155. plate.append(text)
  156.  
  157. config1 = ("-l platenum --psm 10")
  158. x = cropped_imageList[8]
  159. ret, threshed_x = cv2.threshold(cv2.cvtColor(x, cv2.COLOR_BGR2GRAY),
  160. 127, 255, cv2.THRESH_BINARY)
  161. text = pytesseract.image_to_string(threshed_x, config=config1)
  162. text = pytesseract.image_to_string(x, config=config1)
  163. plate.append(text)
  164.  
  165. text = 'R'
  166. plate.append(text)
  167. text = 'U'
  168. plate.append(text)
  169. text = 'S'
  170. plate.append(text)
  171.  
  172. result = ''.join(plate)
  173. result = result.upper()
  174. print(result)
  175.  
  176. imstack = cropped_imageList[0]
  177. for imgs in cropped_imageList[1:]:
  178. imstack = np.hstack((imstack,imgs))#собственно, все вырезанные контуры
  179.  
  180. #повторная бинаризация, т.к. после масштабирования она слетает
  181. ret, threshed_stack = cv2.threshold(cv2.cvtColor(imstack, cv2.COLOR_BGR2GRAY),
  182. 127, 255, cv2.THRESH_BINARY)
  183.  
  184. cv2.drawContours(img, contours, -1, (255, 255, 0), 1) #отрисовать котуры
  185.  
  186. #для проверки
  187. boxesBasic = sorted(boxesBasic)
  188. print(boxesBasic)
  189. cv2.imshow('123', imstack)
  190.  
  191. #вывести на экран, если нужно
  192. threshed_stack = cv2.resize(threshed_stack, (900,300))
  193. cv2.imshow("threshed_numbers", threshed_stack)#вырезанные контуры
  194. cv2.imshow("contours", img)#пикча для проверки правильности контуров
  195. cv2.waitKey(0)
  196. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement