projekt_widzenie/crop_hand_skeleton.py

40 lines
1.3 KiB
Python

import os
from cvzone.HandTrackingModule import HandDetector
import cv2
def crop_hand(img, detector, offset=50):
hands, det_img = detector.findHands(img.copy())
offset = int((img.shape[0] + img.shape[1]) * 0.1)
if hands:
hand = hands[0]
x, y, w, h = hand['bbox']
img_crop = det_img[max(0, y - offset):min(y + h + offset, img.shape[0]), max(0, x - offset):min(x + w + offset, img.shape[1])]
return img_crop
return img
def main():
input_path = "test_data"
output_path = "test_data_cropped"
dir_list = os.listdir(input_path)
detector = HandDetector(maxHands=1, mode=True, detectionCon=0.7, minTrackCon=0.8)
for sign in dir_list:
if not os.path.exists(output_path + '/' + sign):
os.mkdir(output_path + '/' + sign)
for img_name in os.listdir(input_path + '/' + sign):
file_path = input_path + '/' + sign + '/' + img_name
output_file_path = output_path + '/' + sign + '/cropped_' + img_name
img = cv2.imread(file_path)
img_crop = crop_hand(img, detector)
try:
cv2.imwrite(output_file_path, img_crop)
except:
cv2.imwrite(output_file_path, img)
if __name__ == "__main__":
main()