我有几个人的步态数据集。以下是图片:
inputImage
我正在尝试移除背景,以便在生成的图像中仅包含人物,并且尝试从该人物中提取轮廓。以下是我尝试获得所需结果的代码:
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread("inputImage.jpg")
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
grayImage = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
ret, thresh = cv2.threshold(
grayImage,
120,
255,
cv2.THRESH_BINARY_INV)
plt.imshow(thresh, cmap="gray", vmin=0, vmax=255),plt.show()
"""
nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(
thresh,
None,
None,
None,
8,
cv2.CV_32S)
sizes = stats[1:, -1]
img2 = np.zeros((labels.shape), np.uint8)
for i in range(0, nlabels - 1):
if sizes[i] >= 25: #filter small dotted regions
img2[labels == i + 1] = 255
thresh = cv2.bitwise_not(img2)
plt.imshow(thresh, cmap="gray", vmin=0, vmax=255),plt.show()
"""
kernel = np.ones((3,3),np.uint8)
opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)
sure_bg = cv2.dilate(opening,kernel,iterations=20)
dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg,sure_fg)
ret, markers = cv2.connectedComponents(sure_fg)
markers = markers+1
markers[unknown==255] = 0
markers = cv2.watershed(image,markers)
image[markers == -1] = [255,0,0]
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (10,10,665,344)
cv2.grabCut(image,markers,rect,bgdModel,fgdModel,50,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((markers==2)|(markers==0),0,1).astype('uint8')
image = image*mask2[:,:,np.newaxis]
plt.imshow(image, cmap="gray", vmin=0, vmax=255),plt.show()
通过减去以下结果得到的图像
1)阈值:
outputImage1
2)糟透了
outputImage2
这是问题所在。预期的最终图像应该只是人体轮廓。我想要做的就是获得以下最终图像:
groundtruth
如果可能的话,我将在人体步态分类项目中使用结果,不仅在这种特定情况下,即我具有不同的人体步态数据集,请以一般的方式指导我。这样做可能是最好的方式。谢谢您的帮助。