data-writer.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import cv2
  2. import pytesseract
  3. import time
  4. from datetime import datetime
  5. from pytesseract import Output
  6. import cv2
  7. import pytesseract
  8. from pytesseract import Output
  9. import numpy as np
  10. import re
  11. import os
  12. from influxdb import InfluxDBClient
  13. client = InfluxDBClient(host="localhost", port=8086, username="influxdb", password="influxdbTSGAMES", timeout=120_000)
  14. client.create_database("influxdb")
  15. client.switch_database('influxdb')
  16. class SolarMonitor:
  17. camera = None
  18. def __init__(self, test = False):
  19. self.test = test
  20. if not test:
  21. self.initCamera()
  22. def parse(self, img):
  23. custom_oem=r'--oem 3 --psm 7'
  24. # https://github.com/adrianlazaro8/Tesseract_sevenSegmentsLetsGoDigital
  25. data = pytesseract.image_to_data(img, lang='lets', config=custom_oem, output_type=Output.DICT)
  26. #data = pytesseract.image_to_data(img, lang='letsgodigital', config=custom_oem, output_type=Output.DICT)
  27. print(data)
  28. results = []
  29. for i in range(len(data['text'])):
  30. text = data['text'][i].strip('.,-_')
  31. text = re.sub('[^0-9]', '', text)
  32. if text:
  33. results.append(text)
  34. if len(results) == 2:
  35. results = list(map(lambda x: int(x) / 10.,results ))
  36. if results[0] < 80 and results[1] < 900:
  37. return results
  38. return None
  39. def thresholding(self, image):
  40. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  41. pixel_values = image.reshape((-1, 1))
  42. pixel_values = np.float32(pixel_values)
  43. print(pixel_values.shape)
  44. # define stopping criteria
  45. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
  46. # number of clusters (K)
  47. k = 3
  48. _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
  49. # convert back to 8 bit values
  50. centers = np.uint8(centers)
  51. # flatten the labels array
  52. labels = labels.flatten()
  53. # convert all pixels to the color of the centroids
  54. segmented_image = centers[labels.flatten()]
  55. segmented_image = segmented_image.reshape(image.shape)
  56. # disable only the cluster number 2 (turn the pixel into black)
  57. masked_image = np.copy(image)
  58. # convert to the shape of a vector of pixel values
  59. masked_image = masked_image.reshape((-1, 1))
  60. # color (i.e cluster) to disable
  61. cluster = 2
  62. masked_image[labels != cluster] = [0]
  63. # convert back to original shape
  64. masked_image = masked_image.reshape(image.shape)
  65. return masked_image
  66. image = cv2.medianBlur(image,3)
  67. #image = np.invert(image)
  68. return cv2.threshold(image, 140, 255, cv2.THRESH_BINARY)[1]
  69. return image
  70. def thresholding2(self, image):
  71. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  72. # Taking a matrix of size 5 as the kernel
  73. kernel = np.ones((3, 3), np.uint8)
  74. # The first parameter is the original image,
  75. # kernel is the matrix with which image is
  76. # convolved and third parameter is the number
  77. # of iterations, which will determine how much
  78. # you want to erode/dilate a given image.
  79. image = cv2.convertScaleAbs(image, alpha=10.0, beta=-500)
  80. #image = cv2.dilate(image, kernel, iterations=1)
  81. #image = cv2.erode(image, kernel, iterations=1)
  82. #image = cv2.convertScaleAbs(image, alpha=2.0, beta=-50)
  83. #image = (255 - image)
  84. image = cv2.medianBlur(image,3)
  85. #image = np.invert(image)
  86. return image
  87. def crop(self, image):
  88. #top=384
  89. #left=210
  90. #height= 60
  91. #width=230
  92. #return image[top : (top + height) , left: (left + width)]
  93. pt_A = [225, 393]
  94. pt_B = [223, 432]
  95. pt_C = [420, 426]
  96. pt_D = [422, 387]
  97. width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2))
  98. width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2))
  99. maxWidth = max(int(width_AD), int(width_BC))
  100. height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) ** 2))
  101. height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) ** 2))
  102. maxHeight = max(int(height_AB), int(height_CD))
  103. input_pts = np.float32([pt_A, pt_B, pt_C, pt_D])
  104. output_pts = np.float32([[0, 0],
  105. [0, maxHeight - 1],
  106. [maxWidth - 1, maxHeight - 1],
  107. [maxWidth - 1, 0]])
  108. M = cv2.getPerspectiveTransform(input_pts,output_pts)
  109. image = cv2.warpPerspective(image,M,(maxWidth, maxHeight),flags=cv2.INTER_LINEAR)
  110. return image
  111. def initCamera(self):
  112. from picamera import PiCamera
  113. self.camera = PiCamera(
  114. resolution=(800, 608)
  115. )
  116. self.camera.awb_mode = 'off'
  117. self.camera.awb_gains = (1.5, 2.0)
  118. self.camera.shutter_speed = 10000
  119. self.camera.iso = 800
  120. self.camera.rotation = 180
  121. def capture(self):
  122. from picamera.array import PiRGBArray
  123. rawCapture = PiRGBArray(self.camera)
  124. file = "images/" + str(datetime.now()) + ".jpg"
  125. self.camera.capture(rawCapture, format="bgr")
  126. img = rawCapture.array
  127. img = self.crop(img)
  128. print("Captured.")
  129. return [file, img]
  130. def writeData(self, results):
  131. client.write_points([
  132. {
  133. "measurement": "solar",
  134. "tags": {
  135. "type": "U"
  136. },
  137. "fields": {
  138. "value": results[0]
  139. }
  140. },
  141. {
  142. "measurement": "solar",
  143. "tags": {
  144. "type": "W"
  145. },
  146. "fields": {
  147. "value": results[1]
  148. }
  149. }
  150. ], time_precision='ms')
  151. def run(self):
  152. if self.test:
  153. for file in os.listdir('tests'):
  154. img = cv2.imread('tests/' + file)
  155. img = self.thresholding2(img)
  156. results = self.parse(img)
  157. print(file)
  158. print(results)
  159. if results:
  160. self.writeData(results)
  161. cv2.imwrite(file + '_r.jpg', img)
  162. else:
  163. [file, img] = solar.capture()
  164. img = self.thresholding2(img)
  165. results = self.parse(img)
  166. print(results)
  167. if results:
  168. self.writeData(results)
  169. img = cv2.putText(img, str(results), (75, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.25, (255), 1, cv2.LINE_AA)
  170. cv2.imwrite(file + '_r.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 35])
  171. time.sleep(5)
  172. solar = SolarMonitor(test = False)
  173. while True:
  174. solar.run()