Home > database >  How can I segment the object in the image?
How can I segment the object in the image?

Time:07-03

Below are the images that I want to segment the object by white and keep the background in black, tried many methods but can't be able to find the solution;

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

Here is the code:

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()

Do you have any solution for it? to segmentation targeted object perfectly?

CodePudding user response:

Use the following method;

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)
  • Related