Finding boundary of object in image python?

Question:

I was trying to find the boundary of objects in picture and display the contour on the image, which is my problem. I have the following picture here:

Rice

I did the following to extract the contour and plot them on the image:

import cv2
import numpy as np
img = cv2.imread('/home/rama/Downloads/rice.jpg')
rsz_img = cv2.resize(img, None, fx=0.25, fy=0.25) # resize since image is huge
gray = cv2.cvtColor(rsz_img, cv2.COLOR_BGR2GRAY) # convert to grayscale
plt.imshow(gray)
# threshold to get just the signature
    cnts, hierarchy= cnts, hierarchy= cv2.findContours(gray.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
    print(cv2.boundingRect(contour))
    cv2.imshow('img',img)
    cv2.imshow('contour', cv2.boundingRect(contour))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

This gives me just the image as above, no boundary.

How do I plot the boundaries I found on the image?

EDIT SOLUTION:

I did the following:

cnts, hierarchy= cv2.findContours(gray.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in cnts:
    print(cv2.boundingRect(contour))
cv2.drawContours(img,cnts,-1,(125,125,0),3 )
cv2.imshow('contours',img)
cv2.waitKey(0)  
cv2.destroyAllWindows()  

I can see it the first time, when I run it the second time I dont see the image window anymore? I did see the correct boundary the first time!

Asked By: LoveMeow

||

Answers:

You need to use the drawContours() function.

See here: https://docs.opencv.org/3.3.1/d4/d73/tutorial_py_contours_begin.html

Answered By: user2518618
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.