gpt4 book ai didi

python - 如何在 OpenCV Python 中识别图像中的不同对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:29 32 4
gpt4 key购买 nike

我试图在 OpenCV 中识别图像中的单独对象。到目前为止,我已经将图像打开到 NumPy 数组中并对其进行了阈值处理,因此它是二进制的。这是它的样子:

Original Image

我正在尝试识别不同对象所在的 NumPy 数组索引,例如分段。这是我想要实现的目标: End goal (我没有费心用不同的颜色给这张图片中的每个物体上色,但你明白了)

基本上,我试图将每个被视为“对象”的像素簇标记为一个单独的类,并为这些类中的每一个生成一个数组索引列表。我试过使用 OpenCV 的 connectedComponentsWithStats,但我不知道如何为该图像中每个对象的位置生成数组索引列表。我怎样才能做到这一点?

最佳答案

你面对的是connected component labeling所以您可以使用的最佳功能正是您提到的 connectedComponentsWithStats

但是,它的使用在开始时可能会有点困惑。在这里您可以找到一个工作示例。

import cv2
import numpy as np

# Load the image in grayscale
input_image = cv2.imread(r"satellite.png", cv2.IMREAD_GRAYSCALE)

# Threshold your image to make sure that is binary
thresh_type = cv2.THRESH_BINARY + cv2.THRESH_OTSU
_, binary_image = cv2.threshold(input_image, 0, 255, thresh_type)

# Perform connected component labeling
n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(binary_image,
connectivity=4)

# Create false color image
colors = np.random.randint(0, 255, size=(n_labels , 3), dtype=np.uint8)
colors[0] = [0, 0, 0] # for cosmetic reason we want the background black
false_colors = colors[labels]

cv2.imshow('binary', binary_image)
cv2.imshow('false_colors', false_colors)
cv2.waitKey(0)

二值图像:

binary image

图像标记(假色):

labeled image

centroids 变量已包含每个标记对象的质心 (x, y) 坐标。

false_colors_draw = false_colors.copy()
for centroid in centroids:
cv2.drawMarker(false_colors_draw, (int(centroid[0]), int(centroid[1])),
color=(255, 255, 255), markerType=cv2.MARKER_CROSS)
cv2.imshow('false_colors_centroids', false_colors_draw)
cv2.waitKey(0)

质心:

centroids image

如您所见,它们相当多。如果您只想保留较大的对象,您可以 i) 在开始时对二进制图像使用形态学操作或 ii) 使用 stats 中已包含的区域信息。

MIN_AREA = 50
false_colors_draw = false_colors.copy()
for i, centroid in enumerate(centroids[1:], start=1):
area = stats[i, 4]
if area > min_area:
cv2.drawMarker(false_colors_draw, (int(centroid[0]), int(centroid[1])),
color=(255, 255, 255), markerType=cv2.MARKER_CROSS)

质心(按面积过滤):

centroid image filtered

关于python - 如何在 OpenCV Python 中识别图像中的不同对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59150197/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com