输入图像中无效的通道数,K 簇,COLOR_BGR2GRAY

Invalid number of channels in input image, K Clusters, COLOR_BGR2GRAY

我在 jupyter notebook 中有一个程序,它使用 k 表示通过使用主色颜色簇来分割图像。它运行良好,现在我尝试从 PyCharm 程序中添加一些代码,该程序使用阈值在图像上绘制线条。现在我在底部收到此错误。

!pip install opencv-python
!pip install sklearn

import numpy as np
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import cv2

image = cv2.imread('C:\Users\holli\OneDrive\Pictures\python photos\lau black short changing room, haair.jpg')
image.shape

x,y,z= image.shape

plt.imshow(image)

img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

plt.imshow(img)

img = img.reshape(-1,3)

dominant_color = 6
model = KMeans(dominant_color)
model.fit(img)

colors = model.cluster_centers_

colors = np.array(colors, dtype="uint8")

colors

colors = np.array(colors, dtype="uint8")

for i in range(new_image.shape[0]):
    new_image[i] = colors[model.labels_[i]]

new_image = np.reshape(new_image, (x,y,z))

plt.imshow(new_image)

model.labels_

blurred = cv2.medianBlur(img, 5)
grey_blur = cv2.cvtColor(blurred, cv2.cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(grey_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 5)
combined = cv2.bitwise_and(new_image, new_image, mask=thresh)
cv2.imshow("cartoon Lau blk shrt", combined)

reg_img = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)

cv2.imwrite('C:\Users\holli\OneDrive\Pictures\python photos\lai_img_seg.jpg', reg_img)
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
<ipython-input-78-9346139ce50d> in <module>
      1 blurred = cv2.medianBlur(img, 5)
----> 2 grey_blur = cv2.cvtColor(blurred, cv2.cv2.COLOR_BGR2GRAY)
      3 thresh = cv2.adaptiveThreshold(grey_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 15, 5)
      4 combined = cv2.bitwise_and(new_image, new_image, mask=thresh)
      5 cv2.imshow("cartoon Lau blk shrt", combined)

error: OpenCV(4.5.3) c:\users\runneradmin\appdata\local\temp\pip-req-build-c2l3r8zm\opencv\modules\imgproc\src\color.simd_helpers.hpp:92: error: (-2:Unspecified error) in function '__cdecl cv::impl::`anonymous-namespace'::CvtHelper<struct cv::impl::`anonymous namespace'::Set<3,4,-1>,struct cv::impl::A0xb6623f80::Set<1,-1,-1>,struct cv::impl::A0xb6623f80::Set<0,2,5>,2>::CvtHelper(const class cv::_InputArray &,const class cv::_OutputArray &,int)'
> Invalid number of channels in input image:
>     'VScn::contains(scn)'
> where
>     'scn' is 1

我认为我可以 write/save“模糊”图像,然后将其读回并在其上执行其他任务。如果这不起作用,我将不知道还能做什么。

任何人都可以在我的代码中看到任何可能导致此“输入图像中无效的通道数:”错误的内容吗?

img 形状不合适。

如果你想要它是BGR(对于cvtColor),它必须是(something, something, 3)

重塑(展平)后,它只有两个维度,因为你给它的形状 (-1, 3)... cvtColor 解释为单通道(灰度)图像。

您可以将其重塑为 (-1, 1, 3),这是一长列彩色像素:

img.shape = (-1, 1, 3)