Take the following picture as an example :
The name of the picture above is :img_300_320.jpg, Baidu online disk download link :https://pan.baidu.com/s/1IaJ8nrQzGuHt3RA8jbu0GQ?pwd=bjkm
The following code can be used to convert the function findContours() Each contour obtained is drawn separately and saved as a picture file :
# Blogger WeChat /QQ 2487872782
# If you have any questions, you can contact the blogger
# Please contact the blogger if you need image processing
# Image processing technology exchange QQ Group 271891601
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# OpenCV The version is 4.1
import numpy as np
import cv2 as cv
import sys
image = cv.imread('F:/material/images/2022/2022-06/img_300_320.jpg')
if image is None:
print('Error: Could not load image')
sys.exit()
# cv.imshow('Source Image', image)
# The original image is converted into a grayscale image
img_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
# cv.imshow('img_gray', img_gray)
# The gray image is binarized , It's not a function findContours The input image is required to be a binary image ,
# But the function findContours Before contour extraction, the non 0 Value all as 1 Handle .
_, img_B = cv.threshold(img_gray, 71, 255, cv.THRESH_BINARY)
# cv.imshow('img_B', img_B)
# Contour detection
cnts, harch = cv.findContours(img_B, mode=cv.RETR_TREE, method=cv.CHAIN_APPROX_SIMPLE)
img_contours = np.zeros((image.shape[0], image.shape[1]), dtype='uint8')
# Draw each outline separately and save it as bmp picture
for index, cnts_ele in enumerate(cnts):
img_contours = cv.drawContours(img_contours, cnts, index, 255, 1, 1)
str1 = 'F:/temp2/Contours_{:0>2d}.bmp'.format(index)
cv.imwrite(str1, img_contours)
img_contours = 0*img_contours
The operation results are as follows :
I'll pack the results above , It's convenient for you to check , Baidu online disk download link :https://pan.baidu.com/s/18pFc4BqHhGA6e-3-zhj1Ig?pwd=sscs