From 92ea500b6171fe4ff86efb5cd99201404a8937e9 Mon Sep 17 00:00:00 2001 From: Kamil Guttmann Date: Sun, 29 Jan 2023 19:14:37 +0100 Subject: [PATCH] Hand cropping with skeleton --- crop_hand_skeleton.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 crop_hand_skeleton.py diff --git a/crop_hand_skeleton.py b/crop_hand_skeleton.py new file mode 100644 index 0000000..946a7e7 --- /dev/null +++ b/crop_hand_skeleton.py @@ -0,0 +1,39 @@ +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()