cv2.error: OpenCV(4.3.0) Invalid Number of channels in input image

cv2.error: OpenCV(4.3.0) Invalid Number of channels in input image

这是错误代码。

Traceback (most recent call last):
      File "C:\Users\user\Desktop\Python\opencv.py", line 46, in <module>
        color = color_mapping(j)
      File "C:\Users\user\Desktop\Python\opencv.py", line 26, in color_mapping
        return hsv_to_rgb([base % 1.2, 0.95, 0.80])
      File "C:\Users\user\Desktop\Python\opencv.py", line 13, in hsv_to_rgb
        out = cv.cvtColor(in2, cv.COLOR_HSV2RGB)
    cv2.error: OpenCV(4.3.0) c:\projects\opencv-python\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,-1,-1>,struct cv::impl::A0x3b52564f::Set<3,4,-1>,struct cv::impl::A0x3b52564f::Set<0,5,-1>,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

C++代码:graphsegmentation-demo.cpp

/*
By downloading, copying, installing or using the software you agree to this
license. If you do not agree to this license, do not download, install,
copy or use the software.
                          License Agreement
               For Open Source Computer Vision Library
                       (3-clause BSD License)
Copyright (C) 2013, OpenCV Foundation, all rights reserved.
Third party copyrights are property of their respective owners.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
  * Neither the names of the copyright holders nor the names of the contributors
    may be used to endorse or promote products derived from this software
    without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall copyright holders or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused
and on any theory of liability, whether in contract, strict liability,
or tort (including negligence or otherwise) arising in any way out of
the use of this software, even if advised of the possibility of such damage.
*/


#include "opencv2/ximgproc/segmentation.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <fstream>

using namespace cv;
using namespace cv::ximgproc::segmentation;

Scalar hsv_to_rgb(Scalar);
Scalar color_mapping(int);

static void help() {
    std::cout << std::endl <<
    "A program demonstrating the use and capabilities of a particular graph based image" << std::endl <<
    "segmentation algorithm described in P. Felzenszwalb, D. Huttenlocher," << std::endl <<
    "             \"Efficient Graph-Based Image Segmentation\"" << std::endl <<
    "International Journal of Computer Vision, Vol. 59, No. 2, September 2004" << std::endl << std::endl <<
    "Usage:" << std::endl <<
    "./graphsegmentation_demo input_image output_image [simga=0.5] [k=300] [min_size=100]" << std::endl;
}

Scalar hsv_to_rgb(Scalar c) {
    Mat in(1, 1, CV_32FC3);
    Mat out(1, 1, CV_32FC3);

    float * p = in.ptr<float>(0);

    p[0] = (float)c[0] * 360.0f;
    p[1] = (float)c[1];
    p[2] = (float)c[2];

    cvtColor(in, out, COLOR_HSV2RGB);

    Scalar t;

    Vec3f p2 = out.at<Vec3f>(0, 0);

    t[0] = (int)(p2[0] * 255);
    t[1] = (int)(p2[1] * 255);
    t[2] = (int)(p2[2] * 255);

    return t;

}

Scalar color_mapping(int segment_id) {

    double base = (double)(segment_id) * 0.618033988749895 + 0.24443434;

    return hsv_to_rgb(Scalar(fmod(base, 1.2), 0.95, 0.80));

}

int main(int argc, char** argv) {

    if (argc < 2 || argc > 6) {
        help();
        return -1;
    }

    Ptr<GraphSegmentation> gs = createGraphSegmentation();

    if (argc > 3)
        gs->setSigma(atof(argv[3]));

    if (argc > 4)
        gs->setK((float)atoi(argv[4]));

    if (argc > 5)
        gs->setMinSize(atoi(argv[5]));

    if (!gs) {
        std::cerr << "Failed to create GraphSegmentation Algorithm." << std::endl;
        return -2;
    }

    Mat input, input2, output, output_image;

    input2 = imread(argv[1]);

    if (!input2.data) {
        std::cerr << "Failed to load input image" << std::endl;
        return -3;
    }

    resize(input2, input, Size(input2.cols / 10, input2.rows / 10), 0, 0, INTER_LINEAR);

    gs->processImage(input, output);

    double min, max;
    Point minL, maxL;
    minMaxLoc(output, &min, &max, &minL, &maxL);

    std::cout << "Min: " << min << " Max: " << max << " MinL: " << minL << " MaxL: " << maxL << "\n";

    int nb_segs = (int)max + 1;

    std::cout << nb_segs << " segments" << std::endl;

    output_image = Mat::zeros(output.rows, output.cols, CV_8UC3);

    uint* p;
    uchar* p2;

    for (int i = 0; i < output.rows; i++) {

        p = output.ptr<uint>(i);
        p2 = output_image.ptr<uchar>(i);

        for (int j = 0; j < output.cols; j++) {
            Scalar color = color_mapping(p[j]);
            p2[j*3] = (uchar)color[0];
            p2[j*3 + 1] = (uchar)color[1];
            p2[j*3 + 2] = (uchar)color[2];

        }
    }

    imwrite(argv[2], output_image);

    std::cout << "Image written to " << argv[2] << std::endl;

    return 0;
}

我对 Python 的转换:

import cv2 as cv
import sys
import numpy as np

def hsv_to_rgb(c):
    in2 = np.array((1,1,3), np.float32)
    out = np.array((1,1,3), np.float32)

    in2[0] = c[0] * 360.0
    in2[1] = c[1]
    in2[2] = c[2]

    out = cv.cvtColor(in2, cv.COLOR_HSV2RGB) 
 
    t =  [0,0,0]

    t[0] = (int)(out[0] * 255)
    t[1] = (int)(out[1] * 255)
    t[2] = (int)(out[2] * 255)

    return t;


def color_mapping(segment_id):
    base = (segment_id) * 0.618033988749895 + 0.24443434
    return hsv_to_rgb([base % 1.2, 0.95, 0.80])


img = cv.imread("IMG1.jpg", cv.IMREAD_COLOR)

absolute = 10
newdim = (int(img.shape[0]/absolute),int(img.shape[1]/absolute))

img = cv.resize(img, newdim, interpolation = cv.INTER_AREA)

gs = cv.ximgproc.segmentation.createGraphSegmentation()
gs.setSigma(10)
gs.setK(300)
gs.setMinSize(1000)
rimg = gs.processImage(img)

output_image = np.zeros(img.shape, dtype=np.uint8)

for idx1, i in enumerate(rimg):
    for idx2, j in enumerate(i):
        color = color_mapping(j)
        output_image[idx1][idx2*3] = color[0]
        output_image[idx1][idx2*3 + 1] = color[1]
        output_image[idx1][idx2*3 + 2] = color[2]

cv.imshow("Output", output_image);        
cv.waitKey(0)
cv.destroyAllWindows()

我的猜测:

output_image = np.zeros(img.shape, dtype=np.uint8)

output_image = Mat::zeros(output.rows, output.cols, CV_8UC3);

未正确转换?

for (int i = 0; i < output.rows; i++) {

    p = output.ptr<uint>(i);
    p2 = output_image.ptr<uchar>(i);

    for (int j = 0; j < output.cols; j++) {
        Scalar color = color_mapping(p[j]);
        p2[j*3] = (uchar)color[0];
        p2[j*3 + 1] = (uchar)color[1];
        p2[j*3 + 2] = (uchar)color[2];

    }
}

for idx1, i in enumerate(rimg):
    for idx2, j in enumerate(i):
        color = color_mapping(j)
        output_image[idx1][idx2*3] = color[0]
        output_image[idx1][idx2*3 + 1] = color[1]
        output_image[idx1][idx2*3 + 2] = color[2]

数组未正确使用。至少,我不记得可以在 Python 中完成。但是,我找不到解决方案。第二个索引不能展开,而且我认为CV_8UC3应该是一个三通道数组(400,300,3)所以我不明白为什么它要展开第二个维度。

我自己设法解决了这个问题。不过,我会直接向 OpenCV 开发人员解决这个问题,这样他们就能给我答案。

import cv2 as cv
import sys
import numpy as np
import colorsys

def hsv_to_rgb(c):
    in2 = np.array((1,1,3), np.float32)
    out = np.array((1,1,3), np.float32)

    in2[0] = c[0] * 360.0
    in2[1] = c[1]
    in2[2] = c[2]    
    
    out = colorsys.hsv_to_rgb(in2[0],in2[1],in2[2])
 
    t =  [0,0,0]

    t[0] = (int)(out[0] * 255)
    t[1] = (int)(out[1] * 255)
    t[2] = (int)(out[2] * 255)

    return t;


def color_mapping(segment_id):
    base = (segment_id) * 0.618033988749895 + 0.24443434
    return hsv_to_rgb([base % 1.2, 0.95, 0.80])


img = cv.imread("IMG1.jpg", cv.IMREAD_COLOR)

absolute = 5
newdim = (int(img.shape[0]/absolute),int(img.shape[1]/absolute))

img = cv.resize(img, newdim, interpolation = cv.INTER_AREA)

gs = cv.ximgproc.segmentation.createGraphSegmentation()
gs.setSigma(0.001)
gs.setK(10)
gs.setMinSize(50)
rimg = gs.processImage(img)

min = 0.0
max = 0.0
minL = (0,0)
maxL = (0,0)
min, max, minL, maxL = cv.minMaxLoc(rimg)

print("Min: {} Max: {} MinL: {} MaxL: {}".format(min,max,minL,maxL))

nb_segs = max + 1

print("Segments: {}".format(nb_segs))

output_image = np.zeros(img.shape, dtype=np.uint8)

rows, cols = rimg.shape

for idx1 in range(rows):
    for idx2 in range(cols):
        color = color_mapping(rimg[idx1][idx2])
        output_image[idx1][idx2] = color

cv.imwrite("IMG1-XXX.jpg", output_image)

print("Image written to {}".format("IMG1-XXX.jpg"))
cv.imshow("Output", output_image);        
cv.waitKey(0)
cv.destroyAllWindows()

对我的代码的更改:

Used colorsys to change hsv to rgb. The problem might be related to a dimensional, shape or type problem attached to the cvtColor function.

Updated loop. Used range of rows and columns from shape instead of enumerating rows and columns for efficiency. Moreover, the segment to pixel conversion was done removing the index assignment and directly inserting the tuple [R,G,B] into the 400x300 index.