当先锋百科网

首页 1 2 3 4 5 6 7
from skimage.segmentation import slic
from skimage.util import img_as_float
from skimage import io
import numpy as np
import cv2
import random

image_path = 'E:\\PycharmFile\\Image_mass\\nips_car_2.jpg'
segments = 100
args = dict()
args['image'] = image_path
args['segments'] = segments
orig = cv2.imread(args["image"])
image = io.imread(args["image"])
segments = slic(img_as_float(image), n_segments=args["segments"], compactness=15, slic_zero=False) 
w_image, h_image = image.shape[0], image.shape[1]
mask_2 = np.zeros((w_image, h_image, 3))
print('mask_2.shape:', mask_2.shape)

for v in np.unique(segments):
    mask_2[segments == v] = np.array([int(random.randint(1, 254)), int(random.randint(1, 254)), int(random.randint(1, 254))])

mask_3 = mask_2.astype('uint8')
alpha = 0.9  # the wight of mask_3 可理解为“透明度”
output = orig.copy()
cv2.addWeighted(mask_3, alpha, output, 1 - alpha, 0, output)
cv2.imshow('orig', orig)  # 原始图像
cv2.imshow('mask', mask_3)  # 分割图像
cv2.imshow("output", output)  # 原始图像 + 分割图像
cv2.waitKey(0) # 没有这个会出现图像闪退

这是原始图片:在这里插入图片描述

这是分割并填色图片: 在这里插入图片描述这是原始+填色图片在这里插入图片描述