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,

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

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!
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:

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.
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:

The grayscale approach shows a lot of the internal structure of the flower. Whether that is good or bad depends on your objectives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With