for i in range(len(contours)):#遍历所有轮廓 range是从0开始的 cv2.drawContours(mask_water,contours,i,i+1,-1,8,hierarchy)
时间: 2023-10-09 14:06:16 浏览: 108
这段代码使用了一个for循环来遍历所有的轮廓。它使用了range(len(contours))来生成从0到轮廓数量的整数序列,其中len(contours)返回轮廓的数量。在每次迭代中,i表示当前的迭代索引。
然后,cv2.drawContours函数被调用来绘制轮廓。它接受以下参数:
- mask_water:要绘制轮廓的图像。
- contours:轮廓列表。
- i:当前轮廓的索引。
- i+1:当前轮廓的颜色(索引+1)。
- -1:表示填充轮廓。
- 8:线型,表示8邻接。
- hierarchy:层次结构数组。
这段代码的目的是依次绘制所有轮廓,并为每个轮廓分配不同的颜色。
相关问题
def FindContourSinge(k_class, mask_k, contours_info, img_show, times=0): contours, _ = cv2.findContours( mask_k, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE) for i, c in enumerate(contours): area = cv2.contourArea(c) print(f"area {i}:{area}") if area < 200: # 去除小轮廓 continue
这段代码定义了一个名为FindContourSinge的函数,用于在给定的二值图像mask_k中查找轮廓信息,并将这些轮廓信息存储到contours_info列表中。同时,函数还会在img_show上绘制这些轮廓,并通过times参数控制绘制轮廓的次数。具体来说,函数的执行步骤如下:
1.使用cv2.findContours函数在mask_k中查找轮廓信息,并将其存储到contours列表中;
2.遍历contours列表中的每个轮廓,计算其面积area;
3.如果area小于200,则认为这个轮廓是无效的,直接跳过;
4.否则,将轮廓信息存储到contours_info列表中,并在img_show上绘制该轮廓;
5.根据times参数控制绘制轮廓的次数。
需要注意的是,该函数的实现基于OpenCV的cv2模块,因此在使用前需要先导入cv2模块。
for k_class in range(1, n_class): # 遍历每个类找到对应的轮廓, 相当于分类 mask_k = np.zeros((h_mask, m_mask)).astype(np.uint8) mask_k[np.where(mask == k_class)] = 255 FindContourSinge(k_class, mask_k, contours_info, img_show) return img_show, contours_info
这段代码的作用是在二值掩模图像中找到每个类别对应的轮廓,并将轮廓信息保存在一个列表中,最后将轮廓绘制在原始图像上并返回。
具体来说,代码使用`range(1, n_class)`来遍历每个类别,然后通过`np.where(mask == k_class)`找到当前类别在掩模图像中的像素点位置。
接着,将这些像素点位置设置为255,其余位置为0,生成一个新的掩模图像`mask_k`,用于寻找当前类别对应的轮廓。
然后,调用`FindContourSinge`函数,该函数会在`mask_k`中找到当前类别的轮廓,并将轮廓的信息保存在`contours_info`列表中。
最后,将找到的轮廓绘制在原始图像`img_show`上,返回绘制好轮廓的图像和轮廓信息列表`contours_info`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)