为什么find_objects给出一堆 Nones,然后给出整个图像的范围?



我正在尝试查找在帧数差异中检测到的所有对象,我认为这会给出阈值中检测到的每个区域的列表,但是find_objects给出一堆"无"和整个图像的范围?

...
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
None
(slice(0, 972, None), slice(0, 1296, None))

可以从这里测试相关代码

import numpy as np
import cv2
from matplotlib import pyplot as plt
import pylab
from scipy import ndimage
import os
for img in os.listdir('.'):
if img.endswith('.jpg'):
image = cv2.imread(img)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_image = cv2.resize(gray_image, (int(gray_image.shape[1]/2), int(gray_image.shape[0]/2) ))
ret, threshimg = cv2.threshold(gray_image,0,255,cv2.THRESH_BINARY)
cv2.imshow('opening',threshimg)
objects = ndimage.find_objects(threshimg)
for ob in objects:
print(ob)
cv2.waitKey(0)                 # Waits forever for user to press any key   
cv2.destroyAllWindows()

scipy.ndimage.find_objects函数返回

元组列表,每个元组包含 N 个切片(输入数组的维度为 N(。切片对应于包含对象的最小平行六面体。如果缺少数字,则返回 None 而不是切片

我认为在您的数据中,标签不是从 1 开始的(0 是背景,被find_objects忽略(。非 None 的条目的索引是对象的整数值。

您可以使用cv2.connectedComponentsWithStats

import numpy as np
import cv2
from matplotlib import pyplot as plt
import pylab
from scipy import ndimage
import os
### for visualising connected component image
def imshow_components(labels):
# Map component labels to hue val
label_hue = np.uint8(179*labels/np.max(labels))
blank_ch = 255*np.ones_like(label_hue)
labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
# cvt to BGR for display
labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
# set bg label to black
labeled_img[label_hue==0] = 0
return labeled_img
for img in os.listdir('.'):
if img.endswith('.jpg'):
image = cv2.imread(img)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_image = cv2.resize(gray_image, (int(gray_image.shape[1]/2), int(gray_image.shape[0]/2) ))
ret, threshimg = cv2.threshold(gray_image,0,255,cv2.THRESH_BINARY)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh)
out_image=imshow_components(labels)
#### stats will have x,y,w,h,area of each detected connected component

有关连接的组件功能的详细信息,请参阅此答案。

相关内容

最新更新