File size: 2,232 Bytes
b66b75a
2902637
5404db8
 
 
 
2902637
5404db8
 
 
2902637
 
 
 
 
 
 
 
 
 
 
 
 
 
5404db8
 
2902637
5404db8
2902637
 
 
 
 
 
 
 
 
 
 
5404db8
 
 
b66b75a
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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)