Coverage for /opt/conda/envs/apienv/lib/python3.10/site-packages/daiquiri/implementors/imageviewer/autofocus.py: 0%
42 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 02:13 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-14 02:13 +0000
1import time
2import numpy as np
3import cv2
5from daiquiri.core.components import ComponentActor
8class AutofocusActor(ComponentActor):
9 name = "autofocus"
11 def method(self, *args, **kwargs):
12 print("autofocus", self["z_iterations"], self["z_increment"])
14 max_contrast = 0
15 max_contrast_pos = None
17 current = self["z_motor"].get("position")
18 start = current - (self["z_iterations"] * self["z_increment"])
19 for i in range(self["z_iterations"] * 2):
20 position = start + self["z_increment"] * i
22 self["z_motor"].move(position)
23 self["z_motor"].wait()
25 time.sleep(kwargs["camera"].get("exposure") * 1.2)
27 contrast = self.get_canny()
28 print("point", i, position, contrast)
29 if contrast > max_contrast:
30 max_contrast = contrast
31 max_contrast_pos = position
33 print("max contrast", max_contrast, "at", max_contrast_pos)
34 if max_contrast_pos is not None:
35 self["z_motor"].move(max_contrast_pos)
36 self["z_motor"].wait()
38 def get_michelson(self):
39 """Calculate the Michelson contrast
41 https://en.wikipedia.org/wiki/Contrast_(vision)#Michelson_contrast
42 """
43 frame = self["camera"].frame()
44 Y = cv2.cvtColor(frame, cv2.COLOR_RGB2YUV)[:, :, 0]
46 min = np.min(Y)
47 max = np.max(Y)
49 contrast = (max - min) / (max + min)
50 print("min", min, "max", max, "contrast", contrast)
52 return contrast
54 def get_canny(self):
55 """Use canny edge detection to detect frame sharpness
57 https://medium.com/@sedara/how-the-camera-autofocus-feature-works-in-digital-smartphones-8382d511996c
58 https://github.com/opencv/opencv/blob/master/samples/cpp/videocapture_gphoto2_autofocus.cpp
59 """
60 frame = self["camera"].frame()
61 gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
63 gray = cv2.GaussianBlur(gray, (7, 7), 1.5, 1.5)
64 edges = cv2.Canny(gray, 0, 30, 3)
66 total = np.sum(edges) / (frame.shape[0] * frame.shape[1])
67 print("total", total)
69 return total