一种简单的方法是使用 Numpy 切片提取 ROI,像素化,然后将其粘贴回原始图像。我将使用how to pixelate image using OpenCV in Python? 中的像素化技术。这是一个简单的例子:
要提取的输入图像和 ROI
提取的投资回报率
像素化投资回报率
结果
代码
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()
注意: ROI边界框坐标是使用how to get ROI Bounding Box Coordinates without Guess & Check中的脚本找到的。对于您的情况,我假设您已经拥有cv2.boundingRect 获得的x,y,w,h 边界框坐标。