如何分割图像中的对象?



下面是我想用白色分割对象并保持背景为黑色的图像,尝试了很多方法但都不能找到解决方案;

Google Drive: https://drive.google.com/drive/folders/19mWGtxUZccMKtZkcqRO1rcJs2o5thRMq?usp=sharing

代码如下:

def my_method(img):
# convert to hsv
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
L = lab[:, :, 0]
A = lab[:, :, 1]
B = lab[:, :, 2]
# negate A
A = (255 - A)
# multiply negated A by B
nAB = 255 * (A / 255) * (B / 255)
nAB = np.clip((nAB), 0, 255)
nAB = np.uint8(nAB)
# threshold using inRange
range1 = 0
range2 = 255
mask = cv2.inRange(nAB, range1, range2)
mask = 255 - mask
# apply morphology opening to mask
kernel = np.ones((3, 3), np.uint8)
mask = cv2.morphologyEx(mask, cv2.MORPH_ERODE, kernel)
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# antialias mask
mask = cv2.GaussianBlur(mask, (0, 0), sigmaX=3, sigmaY=3, borderType=cv2.BORDER_DEFAULT)
mask = skimage.exposure.rescale_intensity(mask, in_range=(127.5, 255), out_range=(0, 255))
# put white where ever the mask is zero
result = img.copy()
result[mask == 0] = (255, 255, 255)
# write result to disk
cv2.imwrite("mask_result.jpg", mask)
# display it
cv2.imshow("nAB", nAB)
cv2.imshow("mask", mask)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

你有什么解决方案吗?完美分割目标对象?

使用以下方法;

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
h,w, c = img.shape
_, thresh = cv2.threshold(img, np.mean(img), 255, cv2.THRESH_BINARY_INV)
edges = cv2.dilate(cv2.Canny(thresh, 0, 255), None)
cnt = sorted(cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2], key=cv2.contourArea)[-1]
mask = np.zeros((h, w), np.uint8)
masked = cv2.drawContours(mask, [cnt], -1, 255, -1)
dst = cv2.bitwise_and(img, img, mask=masked)
segmented = cv2.cvtColor(dst, cv2.COLOR_BGR2RGB)

最新更新