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

时间:2018-02-06 16:17:32

标签: python image opencv cv2

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

Rice

我做了以下操作来提取轮廓并在图像上绘制它们:

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

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

1 个答案:

答案 0 :(得分:1)

您需要使用drawContours()函数。

见这里:https://docs.opencv.org/3.3.1/d4/d73/tutorial_py_contours_begin.html

相关问题