OpenCV – Is there a way to reliably segment images such as this one?

Question:

Is there a way to reliably segment product images similar to this one? Even just separating the 3 variations from the border would be great. The problem is that the image touches the border, and I don’t know how to deal with that! Not all images are alike, so I need something highly adaptable.

enter image description here

These were the results I achieved using https://docs.opencv.org/master/d3/db4/tutorial_py_watershed.html. My code is identical to the tutorial.

Underwear:

enter image description here

Camera:

enter image description here

What I expected to achieve instead, at least for the image containing the underwear and camera equipment, since the other one is a lot more complex, is for every single object in the image that is not touching another object to be selected separately and outlined in blue. It seems some of the underwear were properly selected as I expected (the first one minus the elastic band) and the first one in the second row (perfectly).

Asked By: José Guedes

||

Answers:

You can use contour as you were going for and take it from the outside. Since the borders are white you invert the threshold so you’ll have something like this:


import numpy as np
import cv2 as cv

im = cv.imread('5zdA0.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)

cv.imshow('image', imgray)
cv.waitKey(0)

ret, thresh = cv.threshold(imgray, 160, 255, 1)
contours, hierarchy = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)


cv.drawContours(imgray, contours, -1, (0,255,0), 3)
cv.imshow('image', imgray)
cv.waitKey(0)

You’ll have to tune these parameters for your images but this should get you going

Answered By: NuLo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.