首页 > 解决方案 > 使用 findContours(cv2) 切片图像

问题描述

由于声誉问题,我无法发布图像,所以这里是我下载的图像的链接:

https://www.amvplaygrounds.co.uk/pub/media/catalog/product/a/m/amv_f4-pm-017-shapes-circle-square-rectangle-star-triangle-200mm-2-sq-3d。 jpg

import cv2
import numpy as np
import matplotlib.pyplot as plt 
image = cv2.imread(r'C:\Users\User\Desktop\shapes.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 200, 255, 0)
contours, hier = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    x,y,w,h = cv2.boundingRect(cnt)
    shape = thresh[y:y+h,x:x+w]
    plt.imshow(shape)

如图所示,它只返回一个轮廓而不是 6 个。

我究竟做错了什么 ?

标签: pythonopencvimage-processing

解决方案


findContours()在黑色背景上寻找白色物体,所以你需要这样的阈值:

ret, thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)  

你需要找到这样的轮廓:

im2, contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) 

推荐阅读