Skip to content

Commit 20b3008

Browse files
committed
add opencv practices
1 parent 4864dbe commit 20b3008

27 files changed

+1115
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import cv2
2+
3+
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
4+
5+
video_capture = cv2.VideoCapture(0)
6+
7+
while True:
8+
# Capture frame-by-frame
9+
ret, frame = video_capture.read()
10+
11+
image_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
12+
13+
detections = face_detector.detectMultiScale(image_gray, minSize=(100,100))
14+
15+
# Draw a rectangle around the faces
16+
for (x, y, w, h) in detections:
17+
print(w, h)
18+
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
19+
20+
# Display the resulting frame
21+
cv2.imshow('Video', frame)
22+
23+
if cv2.waitKey(1) & 0xFF == ord('q'):
24+
break
25+
26+
# When everything is done, release the capture
27+
video_capture.release()
28+
cv2.destroyAllWindows()
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import cv2
2+
3+
face_detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
4+
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
5+
face_recognizer.read("lbph_classifier.yml")
6+
width, height = 220, 220
7+
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
8+
camera = cv2.VideoCapture(0)
9+
10+
while (True):
11+
connected, image = camera.read()
12+
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
13+
detections = face_detector.detectMultiScale(image_gray, scaleFactor=1.5, minSize=(30,30))
14+
for (x, y, w, h) in detections:
15+
image_face = cv2.resize(image_gray[y:y + w, x:x + h], (width, height))
16+
cv2.rectangle(image, (x, y), (x + w, y + h), (0,0,255), 2)
17+
id, confidence = face_recognizer.predict(image_face)
18+
name = ""
19+
if id == 1:
20+
name = 'Jones'
21+
elif id == 2:
22+
name = 'Gabriel'
23+
cv2.putText(image, name, (x,y +(w+30)), font, 2, (0,0,255))
24+
cv2.putText(image, str(confidence), (x,y + (h+50)), font, 1, (0,0,255))
25+
26+
cv2.imshow("Face", image)
27+
if cv2.waitKey(1) == ord('q'):
28+
break
29+
30+
camera.release()
31+
cv2.destroyAllWindows()
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import cv2
2+
3+
#tracker = cv2.TrackerKCF_create()
4+
tracker = cv2.TrackerCSRT_create()
5+
6+
video = cv2.VideoCapture('street.mp4')
7+
ok, frame = video.read()
8+
9+
bbox = cv2.selectROI(frame)
10+
#print(bbox)
11+
12+
ok = tracker.init(frame, bbox)
13+
#print(ok)
14+
15+
while True:
16+
ok, frame = video.read()
17+
#print(ok)
18+
if not ok:
19+
break
20+
ok, bbox = tracker.update(frame)
21+
#print(bbox)
22+
#print(ok)
23+
24+
if ok:
25+
(x, y, w, h) = [int(v) for v in bbox]
26+
cv2.rectangle(frame, (x, y), (x + w, y + h), (0,255,0), 2, 1)
27+
else:
28+
cv2.putText(frame, 'Error', (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)
29+
30+
cv2.imshow('Tracking', frame)
31+
if cv2.waitKey(1) & 0XFF == 27: # ESC
32+
break
33+
Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
1+
pontos = []
2+
3+
def verificar_bracos_ACIMA(pontos):
4+
# BRAÇO ESQUERDO
5+
# posição horizontal
6+
cabeca_V = 0
7+
punhoEsquerdo_H = 0
8+
# posição veritical
9+
ombroEsquerdo_H = 0
10+
punhoEsquerdo_V = 0
11+
12+
# BRAÇO DIREITO
13+
# posição horizontal
14+
punhoDireito_H = 0
15+
# posição veritical
16+
punhoDireito_V = 0
17+
ombroDireito_H = 0
18+
19+
for indx, p in enumerate(pontos):
20+
# BRAÇOS
21+
# 0 ao 8 - ESQUERDO
22+
# 0 ao 5 - DIREITO
23+
# print(indx, p)
24+
# p[0] é na horizontal
25+
# p[1] é na vertical
26+
27+
# CABEÇA
28+
if indx == 0:
29+
cabeca_V = p[1]
30+
31+
# OMBRO DIREITO
32+
elif indx == 2:
33+
ombroDireito_H = p[0]
34+
35+
# PUNHO DIREITO
36+
elif indx == 4:
37+
punhoDireito_H = p[0]
38+
punhoDireito_V = p[1]
39+
40+
# OMBRO ESQUERDO
41+
elif indx == 5:
42+
ombroEsquerdo_H = p[0]
43+
44+
# PUNHO ESQUERDO
45+
elif indx == 7:
46+
punhoEsquerdo_H = p[0]
47+
punhoEsquerdo_V = p[1]
48+
49+
# quanto menor a posição da altura, mais alto o ponto está
50+
# quanto maior a posição da altura, mais baixo o ponto está
51+
# COMPARANDO NA VERITICAL
52+
if punhoEsquerdo_V and punhoDireito_V < cabeca_V:
53+
# print('Punho acima da cabeça')
54+
# COMPARANDO NA HORIZONTAL
55+
if (punhoEsquerdo_H <= ombroEsquerdo_H) and (punhoDireito_H >= ombroDireito_H):
56+
# # print('Punhos passaram da linha do ombro')
57+
return True
58+
else:
59+
return False
60+
61+
62+
def verificar_bracos_ABAIXO(pontos):
63+
# BRAÇO ESQUERDO
64+
# posição horizontal
65+
punhoEsquerdo_H = 0
66+
# posição veritical
67+
ombroEsquerdo_H = 0
68+
ombroEsquerdo_V = 0
69+
punhoEsquerdo_V = 0
70+
71+
# BRAÇO DIREITO
72+
# posição horizontal
73+
# posição veritical
74+
punhoDireito_V = 0
75+
ombroDireito_H = 0
76+
77+
for indx, p in enumerate(pontos):
78+
# OMBRO DIREITO
79+
if indx == 2:
80+
ombroDireito_H = p[0]
81+
ombroDireito_V = p[1]
82+
83+
# PUNHO DIREITO
84+
if indx == 4:
85+
punhoDireito_V = p[1]
86+
87+
# OMBRO ESQUERDO
88+
if indx == 5:
89+
ombroEsquerdo_H = p[0]
90+
ombroEsquerdo_V = p[1]
91+
92+
# PUNHO ESQUERDO
93+
if indx == 7:
94+
punhoEsquerdo_V = p[1]
95+
punhoEsquerdo_H = p[0]
96+
97+
if (punhoEsquerdo_V >= ombroEsquerdo_V) and (punhoDireito_V >= ombroDireito_V):
98+
if (punhoEsquerdo_H <= ombroEsquerdo_H) and (punhoEsquerdo_H >= ombroDireito_H):
99+
print('posicao inicial')
100+
return True
101+
else:
102+
return False
103+
104+
105+
def verificar_pernas_AFASTADAS(pontos):
106+
# PERNAS
107+
# 11 ao 14 a esquerda
108+
# 8 ao 11 a direita
109+
tornozeloEsquerdo_H = 0
110+
tornozeloDireito_H = 0
111+
quadrilEsquerdo_H = 0
112+
quadrilDireito_H = 0
113+
114+
for indx, p in enumerate(pontos):
115+
# print(indx, p)
116+
# p[0] é na horizontal
117+
# p[1] é na vertical
118+
if indx == 0:
119+
quadrilDireito_H = p[0]
120+
if indx == 2:
121+
tornozeloDireito_H = p[0]
122+
if indx == 3:
123+
quadrilEsquerdo_H = p[0]
124+
if indx == 5:
125+
tornozeloEsquerdo_H = p[0]
126+
if (tornozeloDireito_H < quadrilDireito_H) and (tornozeloEsquerdo_H > quadrilEsquerdo_H):
127+
return True
128+
else:
129+
return False
130+
131+
132+
def verificar_pernas_JUNTAS(pontos):
133+
# PERNAS
134+
# 11 ao 14 a esquerda
135+
# 8 ao 11 a direita
136+
tornozeloEsquerdo_H = 0
137+
tornozeloDireito_H = 0
138+
quadrilEsquerdo_H = 0
139+
quadrilDireito_H = 0
140+
141+
for indx, p in enumerate(pontos):
142+
# print(indx, p)
143+
# p[0] é na horizontal
144+
# p[1] é na vertical
145+
if indx == 0:
146+
quadrilDireito_H = p[0]
147+
if indx == 2:
148+
tornozeloDireito_H = p[0]
149+
if indx == 3:
150+
quadrilEsquerdo_H = p[0]
151+
if indx == 5:
152+
tornozeloEsquerdo_H = p[0]
153+
if (tornozeloDireito_H >= quadrilDireito_H) and (tornozeloEsquerdo_H <= quadrilEsquerdo_H):
154+
return True
155+
else:
156+
return False
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import cv2
2+
3+
face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
4+
5+
video_capture = cv2.VideoCapture(0)
6+
7+
while True:
8+
# Capture frame-by-frame
9+
ret, frame = video_capture.read()
10+
11+
image_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
12+
13+
detections = face_detector.detectMultiScale(image_gray, minSize=(100, 100),
14+
minNeighbors=5)
15+
16+
# Draw a rectangle around the faces
17+
for (x, y, w, h) in detections:
18+
print(w, h)
19+
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
20+
21+
# Display the resulting frame
22+
cv2.imshow('Video', frame)
23+
24+
if cv2.waitKey(1) & 0xFF == ord('q'):
25+
break
26+
27+
# When everything is done, release the capture
28+
video_capture.release()
29+
cv2.destroyAllWindows()
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import cv2
2+
import random
3+
import numpy as np
4+
5+
## Generate random colors
6+
def random_colors(N, seed, bright=True):
7+
import colorsys
8+
# To get visually distinct colors, we generate them in HSV space then convert to RGB.
9+
brightness = 1.0 if bright else 0.7
10+
hsv = [(i / N, 1, brightness) for i in range(N)]
11+
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
12+
random.Random(seed).shuffle(colors)
13+
return colors
14+
15+
## Apply mask to image
16+
def apply_mask(image, mask, color, alpha=0.5):
17+
for c in range(3):
18+
image[:, :, c] = np.where(
19+
mask == 1,
20+
image[:, :, c] *
21+
(1 - alpha) + alpha * color[c] * 255,
22+
image[:, :, c])
23+
return image
24+
25+
## Display the instances (segmenteded objects)
26+
def display_instances(image, boxes, masks, class_ids, class_names,
27+
scores=None, title="", figsize=(16, 16), ax=None,
28+
show_mask=True, show_bbox=True, colors=None, captions=None):
29+
from matplotlib import patches, lines
30+
from skimage.measure import find_contours
31+
from matplotlib.patches import Polygon
32+
33+
# Number of instances
34+
N = boxes.shape[0]
35+
if not N:
36+
print("\n*** No instances to display *** \n")
37+
else:
38+
assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]
39+
40+
# Generate random colors
41+
colors = colors or random_colors(N)
42+
43+
height, width = image.shape[:2]
44+
45+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
46+
47+
masked_image = image.astype(np.uint32).copy()
48+
49+
for i in range(N):
50+
color = colors[class_ids[i]]
51+
52+
# Bounding box
53+
if not np.any(boxes[i]):
54+
# Skip this instance. Has no bbox. Likely lost in image cropping.
55+
continue
56+
y1, x1, y2, x2 = boxes[i]
57+
if show_bbox:
58+
p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2,
59+
alpha=0.7, linestyle="dashed",
60+
edgecolor=color, facecolor='none')
61+
62+
# Label
63+
if not captions:
64+
class_id = class_ids[i]
65+
score = scores[i] if scores is not None else None
66+
label = class_names[class_id]
67+
caption = "{} {:.3f}".format(label, score) if score else label
68+
else:
69+
caption = captions[i]
70+
masked_image = cv2.putText(np.float32(masked_image), caption, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255,255,255), 1)
71+
72+
# Mask
73+
mask = masks[:, :, i]
74+
if show_mask:
75+
masked_image = apply_mask(masked_image, mask, color)
76+
77+
# Mask Polygon
78+
# Pad to ensure proper polygons for masks that touch image edges.
79+
padded_mask = np.zeros(
80+
(mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
81+
padded_mask[1:-1, 1:-1] = mask
82+
contours = find_contours(padded_mask, 0.5)
83+
for verts in contours:
84+
# Subtract the padding and flip (y, x) to (x, y)
85+
verts = np.fliplr(verts) - 1
86+
p = Polygon(verts, facecolor="none", edgecolor=color)
87+
88+
return masked_image.astype(np.uint8)
89+
90+
# the functions are based on: https://github.com/matterport/Mask_RCNN/blob/master/mrcnn/visualize.py

0 commit comments

Comments
 (0)