drgs
drgs

Reputation: 117

Function doesn't work properly (OpenCV Python)

I have a problem with the following code :

import cv2
import numpy as np

img = cv2.imread('img.JPG', 0)

def segmentation(image):

    kernel1 = np.ones((3,3), np.float32)/-9.0
    kernel1[1][1] = 8.0/9.0

    filteredImg = cv2.filter2D(image.astype(np.float32), -1, kernel1)

    mrg = cv2.addWeighted(filteredImg.astype(np.float32), 0.9, image.astype(np.float32), 0.1, -20.0)

    retval, th = cv2.threshold(mrg, 1, 10, cv2.THRESH_BINARY_INV)

    kernel2 = np.ones((3,3), np.uint8)

    opening = cv2.morphologyEx(th, cv2.MORPH_OPEN, kernel2, iterations = 2)

    sure_bg = cv2.dilate(opening, kernel2, iterations = 5)

    return sure_bg

def replace(original, mask):

    mask[mask < 128] = 0
    mask[mask > 128] = 1

    outputImg = original * (mask == 0)
    outputImg[mask == 1] = 255

    cv2.imshow('output', outputImg)

replace(img, segmentation(img))
cv2.waitKey(0)
cv2.destroyAllWindows()

The problem is that whenever I run the code, I always get as a result the original image (in this case 'img'). The script should show the segmented part of the image. How can I solve this problem ? Thanks in advance for your help.

Upvotes: 0

Views: 356

Answers (1)

bjou
bjou

Reputation: 1107

Your threshold of 128 on the mask in replace need not necessarily hold. Since the segmentation function will return a matrix of only two possible values, try this instead:

  low, high = np.unique(mask)
  mask[mask == low] = 0
  mask[mask == high] = 1

Everything else looks fine after that.

Upvotes: 1

Related Questions