Search code examples
pythonimage-processingcolorscropopencv

How to change the color for a certain area of an image?


I'm trying to cover the images inside of a paragraph in python.

Here is the original picture and there are two images in the middle of the first paragraph.

enter image description here

Sorry for the big image file.. I want to convert the two images in the middle of the first paragraph into plain white color(to cover them with plain colors). I have the coordinates for these two images, but how can I just change the color in these particular areas?

Here is the x,y coordinates for these two images:

image_1:

left, right = 678, 925
top, bottum = 325, 373

image_2:

left, right = 130, 1534
top, bottum = 403, 1508

Please help! Thank you very much!!


Solution

  • Here's how to "redact" portions of the image given a top-left and bottom-right corner.

    import cv2
    import numpy as np
    
    # load image
    img = cv2.imread("page.jpg");
    
    # target boxes
    boxes = [];
    
    # first box
    tl = [678, 325];
    br = [925, 373];
    boxes.append([tl, br]);
    
    # second box
    tl = [130, 403];
    br = [1534, 1508];
    boxes.append([tl, br]);
    
    # redact with numpy slicing
    for box in boxes:
        tl, br = box;
        img[tl[1]:br[1], tl[0]:br[0]] = [255, 255, 255]; # replace with white
    
    # show image
    cv2.imshow("Redacted", img);
    cv2.waitKey(0);
    cv2.imwrite("redacted.png", img); # save
    

    I don't think the boxes you gave are correct. The second one is huge and the first is tiny. Here's a picture using those boxes:

    enter image description here

    This code should work for any boxes though, so just adjust the corner coordinates to the right spot and it'll work.