RGB颜色分割
对感兴趣区域图像分割出来,操作为选取可以代表感兴趣图像的像素点组成样本集合,通过样本集对待分割的颜色的“平均”进行估计。用向量a表示平均颜色,向量z表示RGB空间中的任一像素点的颜色特征(像素点的RGB这三个分量的值组成的向量)
若z与a的欧氏距离小于给定的阈值,则认为z与a相似。
from skimage import data, io
from matplotlib import pyplot as plt
import numpy as np
import math
image = io.imread('flower.jpg')
r = image[:, :, 0]
g = image[:, :, 1]
b = image[:, :, 2]
r1 = r[128:255, 85:169]
r1_u = np.mean(r1)
r1_d = 0.0
for i in range(r1.shape[0]):
for j in range(r1.shape[1]):
r1_d = r1_d + (r1[i, j] - r1_u) * (r1[i, j] - r1_u)
r1_d = math.sqrt(r1_d / r1.shape[0] / r1.shape[1])
r2 = np.zeros(r.shape, dtype='uint8')
for i in range(r.shape[0]):
for j in range(r.shape[1]):
if (r1_u - 1.25 * r1_d) <= r[i, j] <= (r1_u + 1.25 * r1_d):
r2[i, j] = 1
image2 = np.zeros(image.shape, dtype='uint8')
for i in range(r.shape[0]):
for j in range(r.shape[1]):
if r2[i, j] == 1:
image2[i, j, :] = image[i, j, :]
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.figure()
plt.subplot(231)
plt.axis('off')
plt.imshow(image)
plt.title('原始')
plt.subplot(232)
plt.axis('off')
plt.imshow(r, cmap='gray')
plt.title('R')
plt.subplot(233)
plt.axis('off')
plt.imshow(g, cmap='gray')
plt.title('G')
plt.subplot(234)
plt.axis('off')
plt.imshow(b, cmap='gray')
plt.title('B')
plt.subplot(235)
plt.axis('off')
plt.imshow(r2, cmap='gray')
plt.title('变化后')
plt.subplot(236)
plt.axis('off')
plt.imshow(image2)
plt.show()
#计算样本点红色的标准差
r1_d = 0.0
for i in range(r1.shape[0]):
for j in range(r1.shape[1]):
r1_d = r1_d + (r1[i, j] - r1_u) * (r1[i, j] - r1_u)
#寻找符合条件的点,r2为红色分割图像
r2 = np.zeros(r.shape, dtype='uint8')
for i in range(r.shape[0]):
for j in range(r.shape[1]):
if (r1_u - 1.25 * r1_d) <= r[i, j] <= (r1_u + 1.25 * r1_d):
r2[i, j] = 1