900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)

Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)

时间:2020-04-10 19:37:19

相关推荐

Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)

Python+OpenCV:基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)

##################################################################################################### 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)def lmc_cv_image_segmentation_watershed():"""函数功能: 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)。"""# 读取图像image = lmc_cv.imread('D:/99-Research/Python/Image/water_coins.jpg', flags=lmc_cv.IMREAD_UNCHANGED)rgb_image = lmc_cv.cvtColor(image, lmc_cv.COLOR_BGR2RGB)rgb_image_result = rgb_image.copy()gray_image = lmc_cv.cvtColor(rgb_image, lmc_cv.COLOR_RGB2GRAY)# 基于分水岭算法的图像分割(Image Segmentation with Watershed Algorithm)ret, thresh_image = lmc_cv.threshold(gray_image, 0, 255, lmc_cv.THRESH_BINARY_INV + lmc_cv.THRESH_OTSU)# noise removalkernel = np.ones((3, 3), np.uint8)opening_image = lmc_cv.morphologyEx(thresh_image, lmc_cv.MORPH_OPEN, kernel, iterations=2)# sure background areasure_bg_image = lmc_cv.dilate(opening_image, kernel, iterations=3)# Finding sure foreground areadist_transform = lmc_cv.distanceTransform(opening_image, lmc_cv.DIST_L2, 5)ret, sure_fg_image = lmc_cv.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)# Finding unknown regionsure_fg_image = np.uint8(sure_fg_image)unknown = lmc_cv.subtract(sure_bg_image, sure_fg_image)# Marker labellingret, markers_image = lmc_cv.connectedComponents(sure_fg_image)# Add one to all labels so that sure background is not 0, but 1markers_image = markers_image + 1# Now, mark the region of unknown with zeromarkers_image[unknown == 255] = 0markers_image = lmc_cv.watershed(rgb_image_result, markers_image)rgb_image_result[markers_image == -1] = [255, 0, 0]# 显示图像pyplot.figure('Image Display')titles = ['Original Image', 'Thresh Image', 'ForeGround Image', 'BackGround Image', 'Distance Transform Image','Markers Image', 'Result Image']images = [rgb_image, thresh_image, sure_fg_image, sure_bg_image, dist_transform, markers_image, rgb_image_result]for i in range(7):pyplot.subplot(2, 4, i + 1)pyplot.imshow(images[i], 'gray')pyplot.title(titles[i])pyplot.xticks([])pyplot.yticks([])pyplot.show()# 根据用户输入保存图像if ord("q") == (lmc_cv.waitKey(0) & 0xFF):# 销毁窗口pyplot.close('all')return

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。