Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pixelate ROI bounding box and overlay it on original image using OpenCV

Lets make it straightforward.

I have private project to block or pixelate image using boundary box in open-cv, something like censoring image, inspired from this paper:

https://www.researchgate.net/publication/325746502_Seamless_Nudity_Censorship_an_Image-to-Image_Translation_Approach_based_on_Adversarial_Training

I have found the way to classify the area of censor using Keras, but still don't know the way how to use the boundary box to pixelate the classified area, and overlay it to original image. Any help are appreciated.

This is the example of the process that I want to do:

enter image description here


1 Answers

A simple method is to extract the ROI using Numpy slicing, pixelate, then paste it back into the original image. I will be using the pixelation technique found in how to pixelate image using OpenCV in Python?. Here's a simple example:


Input image and ROI to be extracted

Extracted ROI

Pixelated ROI

Result

Code

import cv2

def pixelate(image):
    # Get input size
    height, width, _ = image.shape

    # Desired "pixelated" size
    h, w = (16, 16)

    # Resize image to "pixelated" size
    temp = cv2.resize(image, (w, h), interpolation=cv2.INTER_LINEAR)

    # Initialize output image
    return cv2.resize(temp, (width, height), interpolation=cv2.INTER_NEAREST)

# Load image
image = cv2.imread('1.png')

# ROI bounding box coordinates
x,y,w,h = 122,98,283,240

# Extract ROI
ROI = image[y:y+h, x:x+w]

# Pixelate ROI
pixelated_ROI = pixelate(ROI)

# Paste pixelated ROI back into original image
image[y:y+h, x:x+w] = pixelated_ROI

cv2.imshow('pixelated_ROI', pixelated_ROI)
cv2.imshow('image', image)
cv2.waitKey()

Note: The ROI bounding box coordinates were found by using the script in how to get ROI Bounding Box Coordinates without Guess & Check. For your case, I will assume that you already have the x,y,w,h bounding box coordinates obtained by cv2.boundingRect.

like image 83
nathancy Avatar answered Dec 07 '25 05:12

nathancy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!