Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the shape of an object in an image using python [closed]

Tags:

python

image

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!

like image 254
varsha_holla Avatar asked Nov 25 '25 15:11

varsha_holla


1 Answers

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.

like image 193
John1024 Avatar answered Nov 27 '25 04:11

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!