我有大量的航拍图像。其中一些镜头被部分遮挡。例如:
和
我正在尝试使用 OpenCV 自动检测哪些图像具有此功能。我最初的目的是检查多个图像中有多少图像是黑色的。但希望有一种聪明的方法可以单独处理图像。
我有大量的航拍图像。其中一些镜头被部分遮挡。例如:
和
我正在尝试使用 OpenCV 自动检测哪些图像具有此功能。我最初的目的是检查多个图像中有多少图像是黑色的。但希望有一种聪明的方法可以单独处理图像。
一个想法是确定图像上有多少黑色像素。我们可以通过创建一个空白蒙版,然后使用在蒙版上将所有检测到的黑色像素着色为白色来做到这一点np.where
。从这里我们可以计算蒙版上白色像素的数量,cv2.countNonZero
然后计算像素百分比。如果计算的百分比大于某个阈值(例如 2%),则图像被部分遮挡。结果如下:
输入图像->
掩码
Pixel Percentage: 3.33%
Occluded: True
Pixel Percentage: 2.54%
Occluded: True
代码
import cv2
import numpy as np
def detect_occluded(image, threshold=2):
"""Determines occlusion percentage and returns
True for occluded or False for not occluded"""
# Create mask and find black pixels on image
# Color all found pixels to white on the mask
mask = np.zeros(image.shape, dtype=np.uint8)
mask[np.where((image <= [15,15,15]).all(axis=2))] = [255,255,255]
# Count number of white pixels on mask and calculate percentage
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
h, w = image.shape[:2]
percentage = (cv2.countNonZero(mask)/ (w * h)) * 100
if percentage < threshold:
return (percentage, False)
else:
return (percentage, True)
image = cv2.imread('2.jpg')
percentage, occluded = detect_occluded(image)
print('Pixel Percentage: {:.2f}%'.format(percentage))
print('Occluded:', occluded)
我建议使用某种带有黑色像素的填充算法。通过检查大的(连接的)黑色区域,您可以识别这些。这种方法的优点是您可以调整参数以提高攻击性(例如,何时将像素标记为黑色,连接区域必须有多大等)。