-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsegmentation.py
80 lines (62 loc) · 2.23 KB
/
segmentation.py
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
import numpy as np
def segment_hand_with_background(picture):
hsv_img = cv2.cvtColor(picture, cv2.COLOR_BGR2HSV)
lower = (40, 60, 50)
higher = (100, 255, 255)
mask = cv2.inRange(hsv_img, lower, higher)
masked = cv2.bitwise_and(hsv_img, hsv_img, mask=mask)
binary_image = to_binary(masked)
binary_image = change_binary_image_colors(binary_image)
kernel = np.ones((5, 5), np.uint8)
return rotate_while_not_aligned(morphology_filter(binary_image, kernel))
def segment_hand_with_skin(picture):
# needs some improvement
min_YCrCb = (0, 100, 50)
max_YCrCb = (250, 180, 160)
imageYCrCb = cv2.cvtColor(picture, cv2.COLOR_BGR2YCR_CB)
skinRegionYCrCb = cv2.inRange(imageYCrCb, min_YCrCb, max_YCrCb)
masked = cv2.bitwise_and(picture, picture, mask=skinRegionYCrCb)
binary_image = to_binary(masked)
kernel = np.ones((5, 5), np.uint8)
return rotate_while_not_aligned(morphology_filter(binary_image, kernel))
def to_binary(img):
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, binary_image = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
return binary_image
def morphology_filter(img, kernel):
img = cv2.dilate(img, kernel)
img = cv2.erode(img, kernel, iterations=2)
return cv2.dilate(img, kernel)
def change_binary_image_colors(binary_image):
h = binary_image.shape[0]
w = binary_image.shape[1]
# loop over the image, pixel by pixel
for y in range(0, h):
for x in range(0, w):
# threshold the pixel
if binary_image[y, x] == 255:
binary_image[y, x] = 0
else:
binary_image[y, x] = 255
return binary_image
def rotate_while_not_aligned(segmented):
last_column = 0
h = segmented.shape[0]
w = segmented.shape[1]
for y in range(0, h):
if segmented[y, w - 1] == 255:
last_column += 1
trial = 0
while last_column < 50:
trial = trial + 1
last_column = 0
segmented = np.rot90(segmented)
h = segmented.shape[0]
w = segmented.shape[1]
for y in range(0, h):
if segmented[y, w - 1] == 255:
last_column += 1
if trial == 4:
break
return segmented