| 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 |
| |
| 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 |
| |
| total_pixel_count_left = result_left.size |
| black_pixels_count_left = total_pixel_count_left - cv2.countNonZero(result_left) |
| |
| total_pixel_count_right = result_right.size |
| black_pixels_count_right = total_pixel_count_right - cv2.countNonZero(result_right) |
|
|
| |
| if black_pixels_count_left >= total_pixel_count_left*inversion_threshold: |
| |
| 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) |