-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_cells.py
More file actions
80 lines (68 loc) · 2.21 KB
/
Copy pathinput_cells.py
File metadata and controls
80 lines (68 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import cv2
from picamera2 import Picamera2, Preview
import time
from time import sleep
# Constants make clear which number refers to which color
# later in the code.
WHITE = 0
BLACK = 1
GREEN = 2
# Captures an image of one cell along the tape.
def captureImage():
cam = Picamera2()
camera_config = cam.create_still_configuration(main={"size": (1920, 1080)}, lores={"size": (640, 480)}, display="lores")
cam.configure("camera_config")
cam.start_preview(Preview.QTGL)
cam.start()
time.sleep(1)
cam.capture_file("cell.jpg")
cam.close()
# Sums up red, green, and blue pixels in the part of the image
# where the square cell should be located. Then uses the average
# amount of red, green, and blue to assign a color: white,
# black, or green.
def detectColor():
image = cv2.imread("cell.jpg", cv2.IMREAD_COLOR)
num_rows, num_cols, _ = image.shape
bound = 200
red_sum = 0.0
green_sum = 0.0
blue_sum = 0.0
for row in range(bound, num_rows-bound):
for col in range(bound, num_cols-bound):
red, green, blue = image[row][col]
red_sum += red
green_sum += green
blue_sum += blue
num_pixels = (num_rows - 2 * bound) * (num_cols - 2 * bound)
red_avg = red_sum / num_pixels
green_avg = green_sum / num_pixels
blue_avg = blue_sum / num_pixels
cell_color = WHITE
if green_avg > red_avg + 40 and green_avg > 100:
cell_color = GREEN
elif red_avg + blue_avg + green_avg / 3 < 100:
cell_color = BLACK
return cell_color
# Repeatedly captures images of cells along the physical tape
# and determines their color. Black cells are recorded as 1s
# into "tape", and white cells as 0s. A green cell ends this
# process, after which "tape" is recorded into tape.txt.
def main():
tape = [0]
index = 0
while (tape[index] != GREEN):
captureImage()
tape.append(detectColor())
index += 1
tape.pop(index)
tape.pop(0)
line = str(tape)[1:-1]
line = line.replace(",", "")
line = line.replace(" ", "")
file = open("tape.txt", "w")
file.writelines(line)
file.close()
# Call main() if this file is run directly.
if __name__ == "__main__":
main()