from skimage.segmentation import slic from skimage.segmentation import mark_boundaries from skimage.util import img_as_float import matplotlib.pyplot as plt import numpy as np import cv2 # args args = {"image": 'I:\\18Breakageratecalculation\\SVM run\\images\\001.jpg'} # load the image and apply SLIC and extract (approximately) # the supplied number of segments image = cv2.imread(args["image"]) segments = slic(img_as_float(image), n_segments=100, sigma=5) # show the output of SLIC fig = plt.figure('Superpixels') ax = fig.add_subplot(1, 1, 1) ax.imshow(mark_boundaries(img_as_float(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), segments)) plt.axis("off") plt.show() print("segments:\n", segments) print("np.unique(segments):", np.unique(segments)) # loop over the unique segment values for (i, segVal) in enumerate(np.unique(segments)): # construct a mask for the segment print("[x] inspecting segment {}, for {}".format(i, segVal)) mask = np.zeros(image.shape[:2], dtype="uint8") mask[segments == segVal] = 255 # show the masked region cv2.imshow("Mask", mask) cv2.imshow("Applied", np.multiply(image, cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) > 0)) cv2.waitKey(0)怎么保存超像素块
时间: 2024-02-25 19:56:44 浏览: 180
要保存超像素块,你可以在循环中将每个超像素块保存为一个单独的图像文件。例如,你可以在循环内部使用以下代码将每个超像素块保存为一个单独的文件:
```python
cv2.imwrite("segment_%d.png" % i, np.multiply(image, cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) > 0))
```
这将使用当前循环索引 i 作为文件名的一部分,将每个超像素块保存为一个名为 "segment_i.png" 的文件。
阅读全文