cv2.cvtColor error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

cv2.cvtColor error: (-215) scn == 3 || scn == 4 in function cv::cvtColor

我正在尝试使用 kmeans 聚类从图像中获取最常见的颜色。它适用于本地图像,但是 returns 这个错误与从 url 中提取图像的新功能有关。这是抛出错误的行之前的代码:

# import the necessary packages
from sklearn.cluster import KMeans
import numpy as np
import urllib
import argparse
import utils
import cv2

def getCommonColors(url):

    req = urllib.urlopen(url)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr,-1)


    image = cv2.imread(np.array_str(img))
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

如有任何帮助,我们将不胜感激!

或许您可以尝试一下,只是对您的代码进行一些更改..

import numpy as np
import urllib2        #maybe requests is another good choice
import cv2

def getCommonColors(url):

    req = urllib2.urlopen(url)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr,-1)

    # image = cv2.imread(np.array_str(img))   <-- I think you shoudn't use this method, it will return NoneType in python
    image = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)