OpenCV image processing - image segmentation - MeanShift

1. Basic concepts

Strictly speaking, MeanShift is not used to segment images, but smoothing filtering at the color level. It will neutralize the color with similar color distribution, smooth the color details, and erode the small color area. It uses any point P on the image as the center, the radius is sp, and the color amplitude is sr to continuously iterate.

Syntax: pyrMeanShiftFiltering(img, double sp, double sr, maxLevel = 1, termcrit = TermCriteria…)
img: image to be smoothed
sp: detection radius, the larger the blur, the better the effect.
sr: Color amplitude, the larger the color, the more likely it is to be connected together.
The remaining parameters are all default values.

2. Code example

First use MeanShift to smooth the picture, then use Canny to detect the edge, and finally draw the edge, the drawn edge is the foreground.

import cv2


img = cv2.imread('./image/flower.png')
mean_img = cv2.pyrMeanShiftFiltering(img, 20, 30)

# 使用canny检测边缘
canny_img = cv2.Canny(mean_img, 150, 300)

# 检测轮廓
contours, _ = cv2.findContours(canny_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cv2.drawContours(img, contours, -1, (0, 0, 255), 1)

cv2.imshow('img', img)
cv2.imshow('mean_img', mean_img)
cv2.imshow('canny_img', canny_img)
cv2.waitKey(0)

The effect is as follows:
insert image description here

insert image description here

The above is the introduction to the use of the MeanShift() algorithm. If you have any questions, please discuss them in the comment area.

Guess you like

Origin blog.csdn.net/weixin_45153969/article/details/131897589