使用 OpenCV 时输入图像错误中的通道数无效

2023-12-03

cv2.error: OpenCV(4.2.0) c:\projects\opencv
python\opencv\modules\imgproc\src\color.simd_helpers.hpp:92: error:
(-2:Unspecified error) in function '__cdecl cv::impl::`anonymous- 

命名空间'::CvtHelper命名空间'::Set,struct cv::impl::A0xe227985e::Set,struct cv::impl::A0xe227985e::Set,2>::CvtHelper(const 类 CV::_InputArray &,const 类 cv::_OutputArray &,int) > 输入图像中的通道数无效: > 'VScn::包含(scn)' > 哪里 >“scn”为 1

img = cv2.cvtColor(images, cv2.COLOR_BGR2GRAY) 

这行给了我错误

大家好,我是opencv的新手,现在正在做图像分类项目

我的完整代码如下

from flask import Flask, request
from flask_restful import Api, Resource
import sys, os
from myconstants1 import path_logs, path_resources
from logConfig1 import setup_logger
import pathlib, pycountry, cv2, pickle, random, PIL, sys
from pathlib import Path 
import pathlib as pl
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras.utils.np_utils import to_categorical
from keras.layers import Flatten, Dropout
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from PIL import Image, ImageOps
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

logger = setup_logger('/modelTrain', path_logs+'/modelTrain.log')

app = Flask(__name__)
api = Api(app)

path = sys.path
path = Path(__file__).parent

print("path2", path)

class HandleRequest5(Resource):
    y_validation = ""
    x_test = ""
    x_validation  = ""
    x_train = ""
         
    @classmethod
    def post(cls, json): 
               
        data = request.get_json()
        
        json = ({
            "Status": "failed",
            "message": "ALL fields are mandatory"
                })
                
        try:
            country_code = data["country_code"].upper()  
            batch_size = data["batch_size"]
            step_per_epoch_val = data["step_per_epoch_val"]
            epoch = data["epoch"]
        except KeyError:
            print(json)
            logger.debug(json)
            return(json)

        
        try:
            country = pycountry.countries.get(alpha_3 = data["country_code"].upper()).name.lower()
            print("country1", country)
            logger.debug(f'country1 : {country}')
            country = country.split()
            country =("_".join(country))
            print("country : ", country)
            logger.debug(f"country : {country}")
            alpha_2 = pycountry.countries.get(alpha_3 = data["country_code"].upper()).alpha_2
            print("alpha_2 : ", alpha_2)
            logger.debug(f"alpha_2 : {alpha_2}")
        except AttributeError:                
            jsonify1 = {
                        "status": "invalid",
                        "message" : "Invalid country_code"
                        }
            print("invalid country_code")
            
            logger.debug({
                        "status": "invalid",
                        "message" : "Invalid country_code"
                        })
            return jsonify1
    
    #   path = rf'{path}/{country}'  # folder with all class folders
        
        labelFile = rf'{path_resources}/{country}/labels.csv'         
        imageDimensions = (99, 200, 3)
        print("imageDimensions:", imageDimensions)
        testRatio = 0.2               # if 1000 images split will 200 for testing
        validationRatio = 0.2  
        print("line 91 is going to execute")
        cls.importImages( cls,testRatio , validationRatio , imageDimensions  ,country , labelFile)   
        
    def importImages(cls, testRatio, validationRatio, imageDimensions, country, labelFile):
        count = 0
        images = []
        classNo = []
        

        p = pl.Path(f'{path_resources}/{country}')                    
        mylist = [x for x in p.iterdir() if x.is_dir()]
        print("mylist1", mylist)
        print("total classs detected :", len(mylist))
        noofClasses = len(mylist)
        print("noofClasses:", noofClasses)
        print("importing classes...")
        
        for x in range(0, len(mylist)):

            myPicList = os.listdir(os.path.join(str(path_resources), str(country)+'//'+str(count))) 
            print("myPicList1:", myPicList)

            #for y in myPicList:
                #print(os.path.join(path, str(count), y))
                #curImg = cv2.imread((str(path_resources)+"/"+str(count)+"//"+y))
                
            for y in myPicList:
                print(os.path.join(path_resources, country, str(count)+y))

                curImg = cv2.imread(f"{path_resources}{country}/{str(count)}//{y}")                                                      
                images.append(curImg)
                classNo.append(count)
            print(count, end = " ")
            count+=1
        print(" ")
        images = np.array(images, dtype=np.uint8) 
        images = np.array(images)
        print("line 128")
        print(images.shape)
        #images = np.append(images,4)
        #images = images.append((Image.fromarray(images, dtype=np.float32).convert('RGB') / 255.))
#        image = Image.fromarray(images)
        #images = images.convert("RGB")
        classNo = np.array(classNo)        
        
        cls.splitData(cls,images, classNo, testRatio, validationRatio , imageDimensions, labelFile, noofClasses)
        return images, classNo, noofClasses
        
        # split data #
    def splitData(cls, images, classNo, testRatio, validationRatio , imageDimensions, labelFile, noofClasses):

        x_train, x_test, y_train, y_test = train_test_split(images, classNo, test_size = testRatio)
        x_train, x_validation, y_train, y_validation = train_test_split(x_train, y_train , test_size = validationRatio)
        
        # to check if no of images matches to number of labels for each data set
        print("data shapes...")
        print("train : ", end = "");print(x_train.shape, y_train.shape)
        print("validation :", end = ""); print(x_validation.shape, y_validation.shape) 
        print("test :", end = ""); print(x_test.shape, y_test.shape)        
        
        assert (x_train.shape[0] == y_train.shape[0]),  "the no of images is not equal to the no of labels in training set"
        assert (x_validation.shape[0] == y_validation.shape[0]), "the no of images is not equal to the no of labels in validation set"
        assert (x_test.shape[0] == y_test.shape[0]), "the no of images is not equal to the no of labels in test set"
        #print(x_train.shape)
        assert (x_train.shape[1:]  == (imageDimensions)),  "the dimension of training images are wrong"
        assert (x_validation.shape[1:] == (imageDimensions)), "the dimension of validation images are wrong"
        assert (x_test.shape[1:] == (imageDimensions)), "the dimension of test images are wrong"        
        
        data = pd.read_csv(labelFile) 
        
        cls.grayscale(cls, images, x_train, x_validation, x_test, y_train, y_validation, y_test )
        
        return images, x_train, x_validation, x_test, y_train, y_validation, y_test
        # preprocessing the image #

    def grayscale(cls,images, x_train, x_validation, x_test, y_train, y_validation, y_test):
        #images = ImageOps.grayscale(images)
        images = cv2.cvtColor(images, cv2.COLOR_BGR2GRAY)
        cls.equalize(images)
        return images
        
    def equalize(images):
        img = cv2.equalizeHist(images)       
        cls.preprocessing(img, grayscale, equalize)
        return img
        
    def preprocessing(cls, img, grayscale, equalize, x_train, x_validation, x_test, y_train, y_test, y_validation):
        img = grayscale(img)  #convert to grayscale
        img = equalize(img)   #standardize the lightining of an image
        img = img/255         # to normaize value between 0 and 1 instead of 0 to 255
        return img , x_train, x_validation, x_test, y_train, y_test, y_validation

        x_train = np.array(list(map(preprocessing, x_train)))  # to iterate and preprocess all images
        x_validation = np.array(list(map(preprocessing, x_validation)))
        x_test = np.array(list(map(preprocessing, x_test)))

        #cv2.imshow("grayscale images", x_train[random.randint(0, len(x_train)-1)]) #to check if training is done properly
               
        # add a depth of 1 #

        x_train = x_train.reshape(x_train.shape[0], x_train.shape[1], x_train.shape[2], 1)
        x_validation = x_validation.reshape(x_validation .shape[0], x_validation .shape[1], x_validation .shape[2], 1)
        x_test = x_test.reshape(x_test.shape[0], x_test.shape[1], x_test.shape[2], 1)


    def dataAugmentation(cls, x_train, y_train, noofClasses):
    # augmentation of images to make it more generic #

        dataGen = ImageDataGenerator(width_shift_range = 0.1, 
                             height_shift_range  = 0.1,
                             zoom_range = 0.2,
                             shear_range = 0.1,
                             rotation_range = 10)

        dataGen.fit(x_train)
        batches = dataGen.flow(x_train, y_train, batch_size = 20)
        x_batch, y_batch = next(batches)


# to show augmentated image sample 
#fig, axs = plt.subplots(24, 2, figsize = (20, 5))
#fig.tight_layout()
#print(axs)
#print("axs0:",axs[0])
#print("axs1:",axs[1])
#for i in range(10):
    #axs[i].imshow(x_batch[i].reshape(imageDimensions[0], imageDimensions[1]))
    #axs[0][1].imshow(x_batch[i].reshape(imageDimensions[0], imageDimensions[1]))
    #axs[i].axis("off")
    #axs[0][1].axis('off')
#plt.show()

        y_train = to_categorical(y_train, noofClasses) 
        y_validation = to_categorical(y_validation, noofClasses) 
        y_test = to_categorical(y_test, noofClasses) 
        cls.splitData(y_validations)        
        cls.myModel(noofClasses)
# convolution neural network #

    def myModel(cls, noofClasses, country):
        no_of_filters = 60 
        size_of_filter = (5,5)  #this is kernal that move around the image to get the features 
    
        size_of_filter2 = (3,3) 
        size_of_pool = (2,2)
        no_of_nodes = 200
    
        model = Sequential()
        model.add(Conv2D(no_of_filters, size_of_filter, input_shape = (imageDimensions[0], imageDimensions[1], 1), activation = "relu"))
        model.add(Conv2D(no_of_filters, size_of_filter, activation = "relu"))
        model.add(MaxPooling2D(pool_size = size_of_pool))
    
        model.add(Conv2D(no_of_filters//2, size_of_filter2, activation = "relu"))
        model.add(Conv2D(no_of_filters//2, size_of_filter2, activation = "relu"))
        model.add(Dropout(0.5))
    
        model.add(Flatten())
        model.add(Dense(no_of_nodes, activation = "relu"))
        model.add(Dropout(0.5))
    
    
  #  model.add(Flatten())
        model.add(Dense(noofClasses, activation = "softmax"))
    
    # compile model #
        model.compile(Adam(lr = 0.001), loss = "categorical_crossentropy",  metrics = ["accuracy"])
        return model    
    
    # train #
        model = myModel()

        print(model.summary())
        history = model.fit_generator  (dataGen.flow(x_train, y_train, batch_size = batch_size_val), steps_per_epoch = steps_per_epoch_val, epochs = epoch_val, validation_data = (x_train, y_train))  
        
# plot #

        plt.figure(1)
        plt.plot(history.history["loss"])
        plt.plot(history.history["val_loss"])
        plt.legend(["training", "validation"])

        plt.title("loss")
        plt.xlabel("epoch")
        plt.figure(2)
        plt.plot(history.history["accuracy"])
        plt.plot(history.history["val_accuracy"])

        plt.legend(["training", "accuracy"])
        plt.title("accuracy")
        plt.xlabel("epoch")
        #plt.show()


        score = model.evaluate(x_test, y_test, verbose = 0)
        print("test score: ", score[0])
        print("test accuracy: ", score[1])

    ###############################################################
    #store the model as pickle object #
    #save_path = rf'{path}/{country}'
        pickle_out = open(rf"{path_resources}/{country}.p", "wb")
    #model = model.save(rf'{country}_{epoch_val}.h5')

        pickle.dump(model, pickle_out)
        pickle_out.close()
        print(rf"{country}_model saved...")
        cv2.waitKey(0)        

        
api.add_resource(HandleRequest5, '/modelTrain')
if __name__ == ' __main__ ':
    app.run(debug = False)

正如评论中所建议的,您有两种方法可以做到这一点。您可以迭代每个图像并运行cv2.cvtColor方法或者您可以使用公式直接从 RGB 转换为灰度。 OpenCV 使用 SMPTE Rec。 601换算公式,即:

Y = 0.299*R + 0.587*G + 0.114*B

让我们介绍一下这两种方法。

方法#1

创建一个新的 3D 数组336 x 99 x 200然后迭代 4D 数组中的每个图像,进行转换,然后将其设置到输出中的相应位置。

images_gray = np.zeros(images.shape[:-1], dtype=images.dtype)
for i, img in enumerate(images):
    images_gray[i] = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

方法#2 - 直接使用转换公式

我认为这种方法是最有效的,主要是因为我建议您计算这个向量化:

coeffs = np.array([0.114, 0.587, 0.229])
images_gray = (images.astype(np.float) * coeffs).sum(axis=-1)
images_gray = images_gray.astype(images.dtype)

需要注意两点:第一,由于 OpenCV 以 BGR 格式读取图像,因此每个 RGB 值的权重会颠倒。第二个是我暂时将图像转换为浮点精度,以便您由于浮点系数而保持尽可能高的精度。然后,我们将结果输出转换回与输入图像相同的精度。最后,上面的代码要做的是,对于每个图像的每个像素,我们将每个颜色像素乘以转换公式中看到的权重,然后对这些值求和。上面的代码将以矢量化方式执行,没有循环。

关于图像分类的小注释

我在上面的评论中注意到您正在使用它来执行图像分类。如果您计划使用深度学习框架,通常需要维护一个单例维度来反映通道维度,以便您可以在网络的前向传递中正确进行广播。换句话说,你必须有一个336 x 99 x 200 x 1大批。对于方法#1,只需将输出数组声明为具有四个维度,但在循环中,您需要使用以下方法将单个维度添加到数组的末尾np.newaxis.

images_gray = np.zeros(images.shape, dtype=images.dtype)
for i, img in enumerate(images):
    images_gray[i] = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[..., np.newaxis]

对于方法#2,您可以添加keepdims=True in the sum call:

coeffs = np.array([0.114, 0.587, 0.229])
images_gray = (images.astype(np.float) * coeffs).sum(axis=-1, keepdims=True)
images_gray = images_gray.astype(images.dtype)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 OpenCV 时输入图像错误中的通道数无效 的相关文章

随机推荐

  • 在 Scala 中,为什么我不能实现这样一个简单的通用函数?

    我想要一个名为 double 的通用函数 其行为如下 可以应用于任何类型def x T T method double A gt AA double 1 gt 2 double 0 2 gt 0 4 所以我这样写这个函数 def doubl
  • 为什么 Pytesseract 无法识别黑底白字?

    我有很多像下面这样的图像 我需要使用 pytesseract 来抓取白色文本 我使用以下代码 但结果并不令人印象深刻 import pytesseract from PIL import Image pytesseract pytesser
  • 分组和连接元组列表

    我有一个对 key val 的列表 其中键和值都是字符串 我想聚合具有重复键的元组 For key1 val1 key2 val2 key3 val3 key1 val4 key2 val5 我要输出 key1 val1 val4 key2
  • 如何将整数编码为其他整数?

    作为后续将 2 个 4 位数字存储在 1 个 8 位数字中 我想知道是否有一个概括 您可以将 n 个 x 位数字存储到 m 个 y 位数字中 例如 也许您可 以将 5 个 8 位数字存储为 3 个 15 位数字 或者可能将 2 个 8 位数
  • 在OpenGL中绘制“点状”形状,与缩放无关

    我正在使用 Qt 和 QWt3D 绘图工具 并扩展它们以提供我需要的一些 3D 和 2D 绘图功能 因此我在此过程中学习了一些 OpenGL 我目前可以使用 OpenGL 绘制点 但只能绘制为圆形 或通过关闭抗锯齿功能绘制为 正方形 这些点
  • Java 不遵循代码? [复制]

    这个问题在这里已经有答案了 这是我认为不遵循代码应该执行的操作的代码片段 public void updateTimeElapsed timeElapsedLabel setText Time elapsed System nanoTime
  • 类成员的使用声明应为成员声明 (C++2003)

    第 7 3 3 段 C 2003 标准指出 类成员的使用声明应为成员声明 这意味着以下给出了语法错误 struct S1 static int var1 using S1 var1 虽然以下编译良好 namespace N2 int var
  • 警告:只有第一个字节会被分配给字符串偏移量

    以下代码在 PHP 7 中运行良好 为什么我在 PHP 8 中看到此警告 str xy str 0 bc 从 PHP 8 开始 尝试使用方数组括号样式替换具有多个字节的字符串偏移量将发出warning 所以你只需要删除多余的字节 c在这种情
  • Restlet - 使用路由器附加资源类时遇到问题

    使用 Restlet 2 1 0 Java SE 版本进行原型设计时 我在将 ServerResource 类映射到 url 时遇到问题 我已经使用 Router attach 方法尝试了很多变体 但没有任何效果 我当前的代码如下所示 pa
  • 按日期分组,当 count() 不产生任何行时为 0

    我正在使用 Postgresql 9 当没有计算行时 我正在与计数和分组作斗争 让我们假设以下架构 create table views date event timestamp with time zone event id intege
  • 如何在代码中进行检查以确保内核模块之间的依赖关系 - Linux Kernel?

    我有两个模块 我希望模块在执行 insmod 或 rmmod 时相互依赖 目前 我的 module2 依赖于 module1 如果我插入 module1 然后 module2 它工作正常 另一方面 反过来则行不通 这在解释上是合乎逻辑的 但
  • 检查 Python 中的字符串是否为“,”的精确形式

    我正在将两个整数组成的字符串转换为一个元组 我需要确保我的字符串的格式完全符合以下形式
  • CountDownTimer - 用户递增。问题

    我有一个关于 CountDownTimer 的问题 我必须制作一个应用程序 允许用户每次单击按钮时将时间时间增加 1 然后 在停止单击按钮后 它会等待三秒钟 然后开始倒计时 我在下面粘贴了我的代码 我的问题是 我似乎无法使数字递增正常工作
  • SWIFT:NSURLSession 将数据转换为字符串

    在我的 iPhone 应用程序 在 SWIFT 中开发 中 我必须与 https 服务 带有参数 进行通信 并且需要分析响应 一切正常 但在某些情况下注意到它没有得到预期的结果 进一步分析我发现这是将服务器响应数据转换为字符串的问题 NSD
  • 如何下载没有 nuget.exe 或 Visual Studio 扩展的 Nuget 包?

    如何下载 NuGet 包 我没有 NuGet Visual Studio 扩展或命令行程序 nuget exe 如何从网络下载 nupack 文件 据我了解 我将能够提取 dll从中获取文件 带有 7 zip 即可正常使用 我碰巧感兴趣的包
  • jQuery代码,看不懂

    我正在查看这段代码 由于我是网页设计的新手 我无法理解它 所以在我的索引页上我有一个谷歌的链接和ext js页面以下代码 这是我的理解 这是错误的 用户点击ok or cancel 因此变量c或者是ok or cancel 现在我不明白有什
  • 计算谷歌地图V3中两点之间的距离

    如何计算 Google 地图 V3 中两个标记之间的距离 类似于distanceFromV2 中的函数 Thanks 如果你想自己计算 那么你可以使用Haversine公式 var rad function x return x Math
  • PHP获取特定用户的数据

    现在我已经创建了一个带有会话的登录表单 我现在需要的是 当用户使用他的用户名和密码登录时 获取他的数据 例如姓名 关于等 并将其放在欢迎页面中 目前我已经创建了这段代码 但是这段代码获取了所有用户数据
  • 可变借用后的不可变引用

    每次使用 Rust 时 我都会遇到与所有权 借用相关的类似问题 因此这里是最简单的一段代码 它说明了我常见的问题 use std cell RefCell struct Res name String impl Res fn new nam
  • 使用 OpenCV 时输入图像错误中的通道数无效

    cv2 error OpenCV 4 2 0 c projects opencv python opencv modules imgproc src color simd helpers hpp 92 error 2 Unspecified