在图像python中查找对象的边界?

在图像python中查找对象的边界?,python,image,opencv,cv2,Python,Image,Opencv,Cv2,我试图在图片中找到物体的边界并在图像上显示轮廓,这是我的问题。我这里有以下图片: 为了提取轮廓并将其绘制在图像上,我执行了以下操作: 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_

我试图在图片中找到物体的边界并在图像上显示轮廓,这是我的问题。我这里有以下图片:

为了提取轮廓并将其绘制在图像上,我执行了以下操作:

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()
这给了我上面的图像,没有边界

如何绘制在图像上找到的边界

编辑解决方案:

我做了以下工作:

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()  

我第一次可以看到它,当我第二次运行它时,我再也看不到图像窗口了?我第一次确实看到了正确的边界

您需要使用drawContours功能


请参见此处:

当我第二次运行它时,我不再看到图像窗口,这是什么意思?如果您终止该进程并重新启动它,它是否有效?如果调用destroyAllWindows,它们消失是正常的,但是如果再次执行程序,它应该会再次工作