import os from cvzone.HandTrackingModule import HandDetector import cv2 def crop_hand(img, detector, offset=30): hands, det_img = detector.findHands(img.copy()) if hands: hand = hands[0] x, y, w, h = hand['bbox'] img_crop = img[y - offset:y + h + offset, x - offset:x + w + offset] 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) 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()