WebCam - Musterlösung

 1import cv2
 2import numpy as np
 3
 4
 5def drawHistogram(gray):
 6    hist, _ = np.histogram(gray, bins=range(256))
 7    hist = np.float32(hist)
 8    hist = hist / np.max(hist)
 9
10    H = 128
11    histImage = np.zeros((H, 256))
12    for bin, value in enumerate(hist):
13        x0, y0 = bin, H
14        x1, y1 = bin, int(H * (1.0 - value))
15        cv2.line(histImage, (x0, y0), (x1, y1), bin / 256.0, 1)
16
17    return histImage
18
19
20def adjustBrightness(gray, brightness, contrast):
21    mean, std = np.mean(gray), np.std(gray)
22
23    norm = brightness + contrast * (gray - mean) / std
24    return np.uint8(np.clip(norm, 0.0, 1.0) * 255.0)
25
26
27if __name__ == "__main__":
28    cap = cv2.VideoCapture(0)
29    if not cap.isOpened():
30        print("Cannot open camera")
31        exit()
32
33    brightness = 0.5
34    contrast = 0.1
35
36    while True:
37        # Capture frame-by-frame
38        ret, frame = cap.read()
39
40        # if frame is read correctly ret is True
41        if not ret:
42            exit()
43
44        cv2.imshow("Kamerabild", frame)
45
46        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
47        cv2.imshow("Graubild", gray)
48        cv2.imshow("Graubild - Histogramm", drawHistogram(gray))
49
50        norm = adjustBrightness(gray, brightness, contrast)
51        cv2.imshow("Normalisiert", norm)
52        cv2.imshow("Normalisiert - Histogramm", drawHistogram(norm))
53
54        key = cv2.waitKey(1)
55        if key == ord("+"):
56            contrast = np.clip(contrast + 0.01, 0.0, 1.0)
57
58        if key == ord("-"):
59            contrast = np.clip(contrast - 0.01, 0.0, 1.0)
60
61        if key == ord("1"):
62            brightness = np.clip(brightness - 0.05, 0.0, 1.0)
63
64        if key == ord("2"):
65            brightness = np.clip(brightness + 0.05, 0.0, 1.0)
66
67        if key == ord("q"):
68            break