如何分割或分割我的图像和标签,使它们可以用作机器学习的特征?



我正在尝试执行像素分类,以使用机器学习(例如SVM, RandomForest等(对图像进行分割。

通过使用图像的灰度值和RGB值并将每个像素与其基本事实相关联,我设法获得了可接受的结果。为了避免发布完整的代码,以下是我在使用完整图像时如何制作功能和标签数组:

img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
feature_img = np.zeros((img.shape[0], img.shape[1], 4))     # container array, first three dimensions for the rgb values, and the last will hold the grayscale
feature_img[:, :, :3] = img
feature_img[:, :, 3] = img_gray
features = feature_img.reshape(feature_img.shape[0] * feature_img.shape[1], feature_img.shape[2])
gt_features = gt_img.reshape(gt_img.shape[0] * gt_img.shape[1], 1)

对于大小512*512的图像,以上内容将给出形状[262144, 4]的特征和形状[262144, 1]的伴随gt_feature。

这为我提供了sklearn.svm.SVCxy,就像上面提到的,这很好用......但是图像非常嘈杂......由于SVM可以很好地处理更高维的数据,我打算通过将图像拆分为窗口来探索这一点。

基于上面的代码,我想将我的图像of size [512, 1024]拆分为大小为[64*64]的块,并使用这些块来训练 SVM。 按照上述格式,我编写了以下代码将我的图像拆分为块,然后将其.reshape()为分类器所需的格式,但它没有按预期工作:

win_size = 64
feature_img = blockshaped(img_gray, win_size, win_size)
feature_label = blockshaped(gt_img, win_size, win_size)
# above returns arrays of shape [128, 64, 64]
features = feature_img.reshape(feature_img.shape[1] * feature_img.shape[2], feature_img.shape[0])
# features is of shape [4096, 128]
label_ = feature_label.reshape(feature_label.shape[0] * feature_label.shape[1] * feature_label.shape[2], 1)
# this, as expected returns ``[524288, 1]``

函数blockshaped来自此处提供的答案:将 2D 数组切片为较小的 2D 数组

我想增加特征数据的维数的原因是,众所周知,SVM 适用于更高维的数据,并且还想看看基于块或补丁的方法是否有助于分割结果。

我将如何以可用于训练分类器的形式排列我已分解为窗口的数据?

我已经思考了5个小时,并阅读了一些书籍来找到答案! 如果你在做细分,你的方法是完全错误的! 当我们使用机器学习方法进行分割时,我们绝对不会改变任何像素位置。 不仅在 SVM 中,而且在神经网络中,当我们接近分割时,我们不使用池化方法,甚至在 CNN 中,我们也使用相同的填充来避免像素移动。

最新更新