Python np.Reformate():基于rgb强度将图像转换为特征阵列

Python np.Reformate():基于rgb强度将图像转换为特征阵列,python,numpy,scikit-learn,computer-vision,mean-shift,Python,Numpy,Scikit Learn,Computer Vision,Mean Shift,我正在尝试使用sklearn的meanshift算法分割彩色图像。 我有以下代码: import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn.datasets.samples_generator import make_blobs import matplotlib.pyplot as plt from itertools import cycle from PIL impo

我正在尝试使用sklearn的meanshift算法分割彩色图像。 我有以下代码:

import numpy as np
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
from itertools import cycle
from PIL import Image

image = Image.open('sample_images/fruit_half.png')
image = np.array(image)

#need to convert image into feature array based on rgb intensities
flat_image = np.reshape(image, [-1,3])
我正在尝试将图像转换为基于rgb强度的特征阵列,以便进行聚类。 但是,我得到以下错误:

ValueError: cannot reshape array of size 3979976 into shape (3)

我不知道为什么会出现这个错误,以及如何解决这个问题。任何见解都将不胜感激

这是因为加载的图像没有RGB值(如果查看尺寸,最后一个是4)

您需要首先将其转换为RGB,如下所示:

image = Image.open('sample_images/fruit_half.png').convert('RGB')
image = np.array(image)

# Now it works
flat_image = np.reshape(image, [-1,3])

这是因为正在加载的图像没有RGB值(如果查看尺寸,最后一个是4)

您需要首先将其转换为RGB,如下所示:

image = Image.open('sample_images/fruit_half.png').convert('RGB')
image = np.array(image)

# Now it works
flat_image = np.reshape(image, [-1,3])

你怎么知道图像没有RGB值?我不明白你说的最后一个维度是4是什么意思。因此,当你加载数据并将其转换为numpy时,你可以使用
image.shape
。它将显示(#行、#列、#特征)。在您的情况下,功能的数量是4,因此不能是RGB值(因为RGB是3)。什么类型的图像会有4个功能?我不完全确定,但RGB可能有3个通道+1个通道以获得透明度。@ceno980 PNG支持RGBA图像,其中A(alpha)通道表示透明度。您如何判断图像没有RGB值?我不明白您所说的最后一个维度是4是什么意思。因此,当您加载数据并将其转换为numpy时,可以使用
image.shape
检查其维度。它将显示(#行、#列、#特征)。在您的例子中,功能的数量是4,因此不能是RGB值(因为RGB是3)。什么类型的图像会有4个功能?我不完全确定,但RGB可能有3个通道+1个通道用于透明度。@ceno980 PNG支持RGBA图像,其中A(alpha)通道表示透明度。