Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

python - 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!!

question from:https://stackoverflow.com/questions/65912098/how-to-change-the-color-for-a-certain-area-of-an-image

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...