文章目录
- 1. 分割图片示例:
- 2. 代码实现:
- 3. 运行结果:
1. 分割图片示例:
2. 代码实现:
from skimage.io import imread, imshow
from skimage import img_as_ubyte # For converting the float image to uint8
from skimage import io, color
from skimage.color import rgb2hsv
from matplotlib import pyplot as plt
import numpy as npimage_path = "img.jpg"
rgb_image = io.imread(image_path)img_hsv = rgb2hsv(rgb_image)
# -------------转换成HSV色彩空间----------------
fig, ax = plt.subplots(1, 3, figsize=(12,4))
ax[0].imshow(img_hsv[:,:,0], cmap='gray')
ax[0].set_title('Hue')
ax[1].imshow(img_hsv[:,:,1], cmap='gray')
ax[1].set_title('Saturation')
ax[2].imshow(img_hsv[:,:,2], cmap='gray')
ax[2].set_title('Value')
plt.show()
# --------------获得每个HSV通道的强度值---------------
fig2, ax2 = plt.subplots(1, 3, figsize=(15, 5))
ax2[0].imshow(img_hsv[:,:,0],cmap='hsv')
ax2[0].set_title('hue')
ax2[1].imshow(img_hsv[:,:,1],cmap='hsv')
ax2[1].set_title('transparency')
ax2[2].imshow(img_hsv[:,:,2],cmap='hsv')
ax2[2].set_title('value')
fig2.colorbar(imshow(img_hsv[:,:,0],cmap='hsv'))
fig2.tight_layout()
plt.show()
# -------------挑选阈值----------------
# refer to hue channel (in the colorbar)
lower_mask = img_hsv[:, :, 0] > 0.08
# refer to hue channel (in the colorbar)
upper_mask = img_hsv[:, :, 0] < 0.5
# refer to transparency channel (in the colorbar)
saturation_mask = img_hsv[:, :, 1] > 0.7mask = upper_mask * lower_mask * saturation_mask
red = rgb_image[:, :, 0] * mask
green = rgb_image[:, :, 1] * mask
blue = rgb_image[:, :, 2] * mask
img_masked = np.dstack((red, green, blue))imshow(img_masked)
plt.show()# Save the masked image as PNG
# io.imsave("img_masked.png", img_as_ubyte(img_masked))
3. 运行结果:
(1)
(2)
(3)