Guest User

CurrencyDetection.py

a guest
Mar 22nd, 2022
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.84 KB | None | 0 0
  1. import numpy as np
  2. import cv2
  3. import os
  4. import pytesseract
  5. from PIL import ImageGrab
  6. from screeninfo import get_monitors
  7.  
  8.  
  9. # strg + k + c / k + u
  10.  
  11. dirname = os.path.dirname(__file__)
  12. sift = cv2.xfeatures2d.SIFT_create()
  13. bf = cv2.BFMatcher(cv2.NORM_L1, crossCheck=True)
  14. pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'
  15.  
  16. # matching threshold for detecting templates
  17. threshold = 0.50
  18.  
  19. currency_path = os.path.join(dirname, 'TrainingImages/')
  20. currency_images = []
  21. currency_names = []
  22. folder_contains = os.listdir(currency_path)
  23. for cl in folder_contains:
  24.     imgCur = cv2.imread(os.path.join(currency_path, cl))
  25.     # imgCurGrey = cv2.cvtColor(imgCur, cv2.COLOR_BGR2GRAY)
  26.     currency_images.append(imgCur)
  27.     currency_names.append(os.path.splitext(cl)[0])
  28.  
  29. screens = get_monitors()
  30. res_main_monitor = screens[0]
  31. screen_w = res_main_monitor.width
  32. screen_h = res_main_monitor.height
  33.  
  34. if screen_w & screen_h == 2560 & 1400:
  35.     tw_loction_x = 200
  36.     tw_location_y = 300
  37.     tw_w = 1300
  38.     tw_h = 1200
  39. elif screen_w & screen_h == 1920 & 1080:
  40.     tw_loction_x = 200
  41.     tw_location_y = 200
  42.     tw_w = 1420
  43.     tw_h = 800
  44. else:
  45.     print("Wrong Resolution")
  46.  
  47. scrn_rec_img = []
  48. match_list = []
  49. match_results = []
  50. scrn_rec_img = ImageGrab.grab(bbox=(tw_loction_x, tw_location_y, tw_w, tw_h))
  51. scrn_rec_img_np = np.array(scrn_rec_img)
  52. test_image = cv2.imread(os.path.join(
  53.     dirname, 'TestingImages/TestImageAllCurrencys.png'))
  54. # override screen recording with testing images
  55. scrn_rec_img = test_image
  56. # img 16 in chaos orb
  57. curr_img = currency_images[15]
  58. matches = cv2.matchTemplate(scrn_rec_img, curr_img, cv2.TM_CCOEFF_NORMED)
  59. min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(matches)
  60. match_y_loc, match_x_loc = np.where(matches >= threshold)
  61. # draw rectangle
  62. curr_width = curr_img.shape[1]
  63. curr_height = curr_img.shape[0]
  64. # max_loc[0]=width [1] = height bboxes are drawn from location top left to bottom right corner
  65. rect_bbxs = []
  66. for (x, y) in zip(match_x_loc, match_y_loc):
  67.     rect_bbxs.append([x, y, curr_width, curr_height])
  68.     rect_bbxs.append([x, y, curr_width, curr_height])
  69. rect_bbxs, weights = cv2.groupRectangles(rect_bbxs, 1, 0.2)
  70. # condenses the list of rectangles to signle detection per area
  71. for (x, y, w, h) in rect_bbxs:
  72.     cv2.rectangle(scrn_rec_img, (x - 4, y - 4), (x + w + 4, y + h + 4), (0, 255, 255), 2)
  73.  
  74. # print(rect_bbxs[0])
  75.  
  76. # currently only takes a sample image later will take a screenshot of active monitor
  77. scrn_rec_img_gray = cv2.cvtColor(scrn_rec_img, cv2.COLOR_BGR2GRAY)
  78. _, thresh1 = cv2.threshold(np.array(scrn_rec_img_gray), 220, 255, cv2.THRESH_BINARY_INV)
  79. # _, thresh1 = cv2.threshold(np.array(scrn_rec_img_gray), 240, 255, cv2.THRESH_OTSU)
  80. # thresh1 = cv2.adaptiveThreshold(scrn_rec_img_gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
  81. # unpacks coordinates of bounding boxes previously detected with template matching. total of 2 boxes are stored in rect_bbx
  82. for (x, y, w, h) in rect_bbxs:
  83.     cropped = thresh1[y:y+h-32, x:x+w-23]
  84.     scaled_up = cv2.pyrUp(cropped)
  85.     # tried scaling up etc to maybe detect easier
  86.     blurred = cv2.GaussianBlur(scaled_up, (5, 5), 0)
  87.     edged = cv2.Canny(blurred, 50, 250, 255)
  88.     # edgefinding with canny
  89.     print(pytesseract.image_to_string(edged, config='digits'))
  90.     # print found digits
  91.     cv2.imshow('test', scaled_up)
  92.     cv2.waitKey(0)
  93.  
  94.  
  95. # blurred = cv2.GaussianBlur(scrn_rec_img_gray, (5, 5), 0)
  96. # edged = cv2.Canny(blurred, 30, 40, 255)
  97.  
  98. # ret, thresh1 = cv2.threshold(scrn_rec_img_gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV)
  99. # rect_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 10))
  100. # dilation = cv2.dilate(thresh1, rect_kernel, iterations=1)
  101. # contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
  102. # img_cpy = scrn_rec_img_gray.copy()
  103. # found_numbers = []
  104. # for cnt in contours:
  105. #     x, y, w, h = cv2.boundingRect(cnt)
  106. #     # Drawing a rectangle on copied image
  107. #     rect = cv2.rectangle(img_cpy, (x, y), (x + w, y + h), (0, 255, 0), 2)    
  108. #     # Cropping the text block for giving input to OCR
  109. #     cropped = img_cpy[y:y + h, x:x + w]
  110. #     text = pytesseract.image_to_string(cropped)
  111. #     found_numbers.append(text)
  112. # print(text)
  113.  
  114.  
  115. added_cur = 0
  116. # for bbox in rect_bbxs:
  117. # cv2.imshow('record', cropped)
  118. # cv2.waitKey()
  119. cv2.destroyAllWindows
  120.  
  121.  
  122. # def findDesc(currency_images):
  123. #     descList = []
  124. #     for img in currency_images:
  125. #         _, des = sift.detectAndCompute(img, None)
  126. #         descList.append(des)
  127. #     return descList
  128.  
  129.  
  130. # def idCurrency(frame, descList):
  131. #     _, des_frame = sift.detectAndCompute(frame, None)
  132. #     bf = cv2.BFMatcher()
  133. #     for des_cur in descList:
  134. #          matches = bf.match(des_cur, des_frame, k=2)
  135. #          for m, n in matches:
  136. #              if m.distance < 0.75 * n.distance:
  137.  
  138.  
  139. # currency_descriptors = findDesc(currency_images)
  140.  
  141.  
  142. # while(True):
  143. #     scrn_rec_img = ImageGrab.grab(bbox=(tw_loction_x, tw_location_y, tw_w, tw_h))
  144. #     scrn_rec_img_np = np.array(scrn_rec_img)
  145. #     frame = cv2.cvtColor(scrn_rec_img_np, cv2.COLOR_BGR2GRAY)
  146. #     cv2.imshow('test', frame)
  147. #     cv2.waitKey(1)
  148. # cv2.destroyAllWindows()
  149.  
  150.  
  151. # test_image = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY)
  152.  
  153. # kp_test, descrpt_test = sift.detectAndCompute(test_image, None)
  154.  
  155. # chaos_orb_image = cv2.imread(os.path.join(
  156. #     dirname, 'TrainingImages/ChaosOrb.png'))
  157. # chaos_orb_image = cv2.cvtColor(chaos_orb_image, cv2.COLOR_BGR2GRAY)
  158.  
  159. # kp_chaos, descrpt_chaos = sift.detectAndCompute(chaos_orb_image, None)
  160. # matches = bf.match(descrpt_chaos, descrpt_test)
  161. # matches = sorted(matches, key=lambda x: x.distance)
  162.  
  163. # img_1 = cv2.drawMatches(chaos_orb_image, kp_chaos, test_image, kp_test, matches[:10], chaos_orb_image, flags=2)
  164. # cv2.imshow('test', img_1)
  165. # cv2.waitKey(0)
  166.  
Advertisement
Add Comment
Please, Sign In to add comment