我有一组 RGB 图像 (1920 x 1080) 的坐标,存储为列表列表,即 RoI(感兴趣区域),如下所示
[[1538, 234, 1626, 313],
[421, 231, 472, 288],
[918, 199, 988, 270],
[802, 0, 963, 114],
[1732, 0, 1909, 108]]
然后,我应用以下条件来更改上面列表中的坐标内的特定像素值,仅通过将像素更改为白色和黑色来突出显示这些 RoI。
for coords in list_of_coords:
roi = orig[coords[1]:coords[3], coords[0]:coords[2]]
roi [(roi > 200)] = 0
roi [(roi < 200)] = 255
我现在如何获取这些新的修改后的像素值并将它们应用到具有一定透明度的原始图像之上?理想情况下,图像的其余部分将是相同的,而这些坐标内的值将在其顶部有一个透明蒙版。
下面是所需输出的示例。我从 Mask RCNN 中获取了这一点,其中在矩形坐标内,添加了轻微的蓝色阴影以突出显示 RoI。矩形框用上面的列表的列表表示,蓝色阴影是根据上述条件进行的操作。
最佳答案
我仍然不确定,如果我完全理解,你想要实现什么,但这是我尝试回答你的问题:
基本上,对于每组坐标,您需要执行以下操作:
- 获取原始图像的 ROI 剪切图。 (你已经拥有了。)
- 生成一些二进制掩码(相对于某些指标或您拥有的任何信息)以指示您想要操作 ROI 内的哪个部分,例如您图片中显示的汽车。在下面的代码中,我选择屏蔽具有高蓝色 channel 值的任何像素。
- 生成与 ROI 大小相同的混合图像,并根据生成的蒙版使用纯色填充所有像素。在下面的代码中,我选择设置一些纯绿色。
- 使用 OpenCV 的
addWeighted
Alpha 混合方法。 - 将更新后的 ROI 剪切图复制回您的原始图像。
这是我的示例图像和坐标的最终输出:
这是我的代码:
import cv2
from matplotlib import pyplot as plt
import numpy as np
# Load image
orig = cv2.imread('path/to/your/image.png')
orig_back = orig.copy()
# Set up list of list of coordinates (i.e. rectangular ROIs)
list_of_coords = [[90, 0, 260, 30],
[60, 180, 100, 250],
[300, 300, 380, 370]]
# Set up alpha for alpha blending
alpha = 0.5
for coords in list_of_coords:
# Get ROI cutout of image
roi = orig_back[coords[1]:coords[3], coords[0]:coords[2]]
roi_back = roi.copy()
# Generate some mask; examplary here: Mask anything with some high
# blue channel value
mask = roi[:, :, 0] > 172
# Generate blend image; exemplary here: Blend with solid green
blend = np.zeros_like(roi)
blend[mask, 1] = 255
# Alpha blending original image with blend image
roi[mask, :] = cv2.addWeighted(roi[mask, :], alpha,
blend[mask, :], 1 - alpha,
0)
# Copy updated ROI cutout back to image
orig[coords[1]:coords[3], coords[0]:coords[2]] = roi
# Add rectangle to image for location
orig = cv2.rectangle(orig,
(coords[0], coords[1]),
(coords[2], coords[3]),
(0, 255, 0),
2)
# Some visualization output for better understanding
plt.figure(0, figsize=(16, 8))
plt.subplot(221)
plt.imshow(cv2.cvtColor(roi_back, cv2.COLOR_BGR2RGB))
plt.title('ROI cutout of image')
plt.subplot(222)
plt.imshow(mask, cmap='gray')
plt.title('Masked portion of ROI with high blue channel value')
plt.subplot(223)
plt.imshow(cv2.cvtColor(blend, cv2.COLOR_BGR2RGB))
plt.title('Blend image, solid green')
plt.subplot(224)
plt.imshow(cv2.cvtColor(roi, cv2.COLOR_BGR2RGB))
plt.title('Updated ROI cutout of image')
plt.tight_layout()
plt.show()
# Final output
cv2.imshow('Original image with updates and rectangles', orig)
cv2.waitKey(0)
cv2.destroyAllWindows()
而且,这是第一个 ROI 的附加可视化:
希望这就是您正在寻找的!
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
Matplotlib: 3.3.1
NumPy: 1.19.1
OpenCV: 4.4.0
----------------------------------------
关于python - 对象检测 - 如何将坐标内的操纵像素重新应用到原始图像以突出显示 RoI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63881400/