skip to Main Content

I want to know how to find the shape of an object in the image and store it in a variable for further use. For instance,

enter image description here

And I want to extract only the shape, something like this(I manipulated the image in photoshop),

enter image description here

I just need the outline of the image, and I want to save it on the disk.I haven’t tried so far, and I’m using python 2.7

Any suggestion are welcome.

Thanks in advance!

3

Answers


  1. As you haven’t tried anything yet, I suggest you to try first 🙂

    Here are some pointers:

    • convert the image to greyscale
    • hold the greyscale image in a numpy array
    • make an histogram to count levels in the image
    • apply a threshold, to remove background
    • you may try adaptive threshold (look on the web)
    • apply an edge-detection algorithm (like Canny)
    • use morphological mathematics like erosion, dilation to get a better result

    Some useful information here: http://scipy-lectures.github.io/advanced/image_processing/

    Login or Signup to reply.
  2. I don’t recommend grayscale for your image. You appear to be interested in red flower versus green background. A simple and clear way to make that distinction in your image to identify with the flower any pixels whose red value is higher than its green value.

    import cv2
    from numpy import array    
    img = cv2.imread('flower.jpg')
    img2 = array( 200  * (img[:,:,2] > img[:,:, 1]), dtype='uint8')
    

    img2 clearly shows the shape of the flower. To get the edges only, you can use a canny edge detector:

    edges = cv2.Canny(img2, 70, 50)
    cv2.imwrite('edges.png', edges)
    

    The resulting file, edges.png, looks like:

    enter image description here

    The next step, if you want, is to extract coordinates of the edges. This can be done with:

    contours, hierarchy = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    

    Documentation on cv2.canny and cv2.findContours can be found here and here, respectively.

    More: What happens if you use grayscale:

    img = cv2.imread('flower.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
    gray1 = cv2.Canny(img, 70, 50)
    cv2.imwrite('gray1.png', gray1)
    

    The resulting image is:

    enter image description here

    The grayscale approach shows a lot of the internal structure of the flower. Whether that is good or bad depends on your objectives.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search