Download Final_Black_White_Patch_inversion.py from jkushwaha/code: direct link, hf CLI and curl.
- Browser
- Download file 2.23 kB
-
https://huggingface.co/jkushwaha/code/resolve/main/Final_Black_White_Patch_inversion.py
- Command line
-
hf download hf://jkushwaha/code/Final_Black_White_Patch_inversion.py
-
curl -L -o Final_Black_White_Patch_inversion.py https://huggingface.co/jkushwaha/code/resolve/main/Final_Black_White_Patch_inversion.py
2.23 kB
| def scan_image_inversion(image_original, image, filter_patch): | |
| inversion_threshold = 0.4 | |
| W, H = image.shape[:2] | |
| filter_size = filter_patch.shape | |
| t = filter_size[0] | |
| cnt = 0 | |
| for y in range((W-t)//t + 1): | |
| roi = image[y*t:(y*t)+t, :] | |
| if (roi.shape[0]<filter_patch.shape[0]): | |
| break | |
| # print(f"roi shape:{roi.shape}, filter_patch shape: {filter_patch.shape}") | |
| width = roi.shape[1] | |
| mid = int(width/2) if width%2==0 else int((width/2)+1) | |
| roi_left = roi[:, :mid] | |
| roi_right = roi[:, mid:] | |
| result_left = cv2.bitwise_or(roi_left, filter_patch[:, :mid]) | |
| result_right = cv2.bitwise_or(roi_right, filter_patch[:, mid:]) | |
| cnt+=1 | |
| # Count black pixels in the result_left | |
| total_pixel_count_left = result_left.size | |
| black_pixels_count_left = total_pixel_count_left - cv2.countNonZero(result_left) | |
| # Count black pixels in the result_right | |
| total_pixel_count_right = result_right.size | |
| black_pixels_count_right = total_pixel_count_right - cv2.countNonZero(result_right) | |
| # Check if 40% pixels are black | |
| if black_pixels_count_left >= total_pixel_count_left*inversion_threshold: | |
| # new_roi = cv2.bitwise_not(roi) | |
| new_roi_left = 255-roi_left | |
| else: | |
| new_roi_left = roi_left | |
| if black_pixels_count_right >= total_pixel_count_right*inversion_threshold: | |
| new_roi_right = 255-roi_right | |
| else: | |
| new_roi_right = roi_right | |
| new_roi = np.concatenate((new_roi_left, new_roi_right), axis=1) | |
| image_original[y*t:(y*t)+t, :] = new_roi | |
| return image_original | |
| def black_patch_inversion(input_image_path, out_image_path): | |
| image = cv2.imread(input_image_path, cv2.IMREAD_GRAYSCALE) | |
| image_original = cv2.imread(input_image_path, cv2.IMREAD_GRAYSCALE) | |
| _, black_white_image = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) | |
| filter_size = 5 | |
| filter_patch = np.zeros((filter_size, black_white_image.shape[1]), dtype=np.uint8) | |
| inverted_image = scan_image_inversion(image_original, black_white_image, filter_patch) | |
| cv2.imwrite(out_image_path, inverted_image) |