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]= 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)