data-writer-opencv.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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="influxdb", port=8086, username="influxdb", password="influxdbTSGAMES")
  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 11'
  24. # https://github.com/adrianlazaro8/Tesseract_sevenSegmentsLetsGoDigital
  25. data = pytesseract.image_to_data(img, lang='lets', config=custom_oem, output_type=Output.DICT)
  26. print(data)
  27. results = []
  28. for i in range(len(data['text'])):
  29. text = data['text'][i].strip('.,-_')
  30. text = re.sub('[^0-9]', '', text)
  31. if text:
  32. results.append(text)
  33. if len(results) == 2:
  34. results = list(map(lambda x: int(x) / 10.,results ))
  35. if results[0] < 100 and results[1] < 1000:
  36. return results
  37. return None
  38. def thresholding(self, image):
  39. image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  40. pixel_values = image.reshape((-1, 1))
  41. pixel_values = np.float32(pixel_values)
  42. print(pixel_values.shape)
  43. # define stopping criteria
  44. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
  45. # number of clusters (K)
  46. k = 3
  47. _, labels, (centers) = cv2.kmeans(pixel_values, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
  48. # convert back to 8 bit values
  49. centers = np.uint8(centers)
  50. # flatten the labels array
  51. labels = labels.flatten()
  52. # convert all pixels to the color of the centroids
  53. segmented_image = centers[labels.flatten()]
  54. segmented_image = segmented_image.reshape(image.shape)
  55. # disable only the cluster number 2 (turn the pixel into black)
  56. masked_image = np.copy(image)
  57. # convert to the shape of a vector of pixel values
  58. masked_image = masked_image.reshape((-1, 1))
  59. # color (i.e cluster) to disable
  60. cluster = 2
  61. masked_image[labels != cluster] = [0]
  62. # convert back to original shape
  63. masked_image = masked_image.reshape(image.shape)
  64. return masked_image
  65. image = cv2.medianBlur(image,3)
  66. #image = np.invert(image)
  67. return cv2.threshold(image, 140, 255, cv2.THRESH_BINARY)[1]
  68. return image
  69. def thresholding2(self, image):
  70. image = cv2.medianBlur(image,7)
  71. #image = np.invert(image)
  72. return image
  73. def crop(self, image):
  74. top=314
  75. left=230
  76. height= 150
  77. width=400
  78. return image[top : (top + height) , left: (left + width)]
  79. def initCamera(self):
  80. from picamera import PiCamera
  81. self.camera = PiCamera(
  82. resolution=(800, 600)
  83. )
  84. self.camera.awb_mode = 'off'
  85. self.camera.awb_gains = (1.5, 2.0)
  86. self.camera.shutter_speed = 60000
  87. self.camera.iso = 800
  88. def capture(self):
  89. file = "/home/pi/solar-monitor/camera/" + str(datetime.now()) + ".jpg"
  90. self.camera.capture(file)
  91. print("Captured.")
  92. img = cv2.imread(file)
  93. img = self.crop(img)
  94. return [file, img]
  95. def writeData(self, results):
  96. client.write_points([
  97. {
  98. "measurement": "solar",
  99. "tags": {
  100. "type": "U"
  101. },
  102. "fields": {
  103. "value": results[0]
  104. }
  105. },
  106. {
  107. "measurement": "solar",
  108. "tags": {
  109. "type": "W"
  110. },
  111. "fields": {
  112. "value": results[1]
  113. }
  114. }
  115. ], time_precision='ms')
  116. def run(self):
  117. if self.test:
  118. for file in os.listdir('tests'):
  119. img = cv2.imread('tests/' + file)
  120. img = self.thresholding2(img)
  121. results = self.parse(img)
  122. print(file)
  123. print(results)
  124. if results:
  125. self.writeData(results)
  126. cv2.imwrite(file + '_r.jpg', img)
  127. else:
  128. [file, img] = solar.capture()
  129. img = self.thresholding2(img)
  130. results = self.parse(img)
  131. print(results)
  132. if results:
  133. self.writeData(results)
  134. cv2.imwrite(file + '_r.jpg', img)
  135. # os.unlink(file)
  136. time.sleep(2)
  137. while True:
  138. solar = SolarMonitor(test = True)
  139. solar.run()