简体   繁体   English

使用对象检测时出现 Open cv 错误

[英]I am getting a Open cv error when working with object detection

import cv2
import numpy as np
from random import shuffle
from tqdm import tqdm
import os

TRAIN_DIR=r'C:\Users\Valued Customer\Desktop\Object detection\train'
TEST_DIR=r'C:\Users\Valued Customer\Desktop\Object detection\test'
IMG_SIZE=300
LR=1e-3
MODEL_NAME = 'dogsvscats-{}-{}.model'.format(LR,'2conv-basic')



def Label_img(img):
    label = img.split('.')[-3]
    if label == 'cat':
        return [1,0]
    elif label == 'dog':
        return [0,1]

def create_train_data():
    training_data = []
    for img in tqdm(os.listdir(TRAIN_DIR)):

        label = Label_img(img)
        path = os.path.join(TRAIN_DIR,img)
        img = cv2.resize(cv2.imread(path),(IMG_SIZE,IMG_SIZE), interpolation = cv2.INTER_AREA)
        training_data.append([np.array(img),np.array(label)])
    shuffle(training_data)
    np.save('train_data.npy',training_data)
    return training_data

def process_test_data():
    testing_data = []
    for img in tqdm(os.listdir(TEST_DIR)):
        path = os.path.join(TEST_DIR,img)
        img_num = img.split('.')[0]
        img = cv2.resize(cv2.imread(path),(IMG_SIZE,IMG_SIZE), interpolation = cv2.INTER_AREA)

        testing_data.append([np.array(img),img_num])
    np.save('testing_data.npy',testing_data)
    return testing_data

train_data = create_train_data()
#if U already have train data then:
#train_data = np.load('train_data.npy',allow_pickle=True)
print('data has been loaded')

import tflearn
from tflearn.layers.conv import conv_2d,max_pool_2d
from tflearn.layers.core import input_data,dropout,fully_connected
from tflearn.layers.estimator import regression
from tflearn.layers.normalization import batch_normalization as bn
import tensorflow as tf
tf.reset_default_graph()

convnet = input_data(shape=[None,IMG_SIZE,IMG_SIZE,3],name='input')

convnet = conv_2d(convnet,32,filter_size=[2,2],activation='relu')
convnet = conv_2d(convnet,64,filter_size=[2,2],activation='relu')
convnet = bn(convnet,trainable=True)
convnet = max_pool_2d(convnet,kernel_size=[3,3])

convnet = conv_2d(convnet,32,filter_size=[2,2],activation='relu')
convnet = conv_2d(convnet,64,filter_size=[2,2],activation='relu')
convnet = bn(convnet,trainable=True)
convnet = max_pool_2d(convnet,kernel_size=[3,3])

convnet = conv_2d(convnet,32,filter_size=[2,2],activation='relu')
convnet = conv_2d(convnet,64,filter_size=[2,2],activation='relu')
convnet = bn(convnet,trainable=True)
convnet = max_pool_2d(convnet,kernel_size=[3,3])

convnet = fully_connected(convnet,1024,activation='relu')
convnet = dropout(convnet,0.8)
convnet = tflearn.layers.normalization.batch_normalization(convnet,trainable=True)


convnet = fully_connected(convnet,2,activation='softmax')
convnet = regression(convnet,
                     optimizer='adam',
                     learning_rate= LR,
                     loss='categorical_crossentropy',
                     name='targets')

model = tflearn.DNN(convnet)

train = train_data[:-500]
test = train_data[-500:]

X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,3)
Y = np.array([i[1] for i in train])

test_x = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,3)
test_y = np.array([i[1] for i in test])

model.fit({'input':X},{'targets':Y},
          n_epoch=5,validation_set=({'input':test_x},{'targets':test_y}),
          snapshot_step=500,show_metric=True,run_id=MODEL_NAME)
#
model.save(MODEL_NAME)





When ever I try to run this code it stops a 21% when it is creating the training data当我尝试运行此代码时,它会在创建训练数据时停止 21%

def create_train_data():
    training_data = []
    for img in tqdm(os.listdir(TRAIN_DIR)):

        label = Label_img(img)
        path = os.path.join(TRAIN_DIR,img)
        img = cv2.resize(cv2.imread(path),(IMG_SIZE,IMG_SIZE), interpolation = cv2.INTER_AREA)

And it keeps giving em a open cv error它不断给他们一个开放的简历错误

error: OpenCV(4.1.1) C:\\projects\\opencv-python\\opencv\\modules\\imgproc\\src\\resize.cpp:3720: error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize错误:OpenCV(4.1.1) C:\\projects\\opencv-python\\opencv\\modules\\imgproc\\src\\resize.cpp:3720: 错误: (-215:Assertion failed) !ssize.empty() in function 'cv ::调整大小

I am on windows ten using cuda for the first (not sure if i set it up right) Also does anyone know how i can check if i am using cuda Thanks我在 Windows 10 上首先使用 cuda(不确定我是否设置正确)还有谁知道我如何检查我是否使用 cuda 谢谢

我今天出现这个错误是因为我的图片路径不对。您可以尝试显示一张图片,看看您是否成功阅读了图片。

So i found a answer to my own question!!!所以我找到了我自己问题的答案!!!

What i did was print the names of the that it was loading in and the image that it stopped on was corrupt.我所做的是打印它正在加载的名称,并且它停止的图像已损坏。 I had to this multiple times.我不得不多次这样做。

Just type this your script or ipython cell to verify if there is an empty or corrupt image that might create this error .只需键入您的脚本或 ipython 单元格以验证是否存在可能导致此错误的空图像或损坏图像。

import os
from PIL import Image

img_dir = r"/content/downloads/Cars"
for filename in os.listdir(img_dir):
    try :
        with Image.open(img_dir + "/" + filename) as im:
             print('ok')
    except :
        print(img_dir + "/" + filename)
        os.remove(img_dir + "/" + filename)

Replace img_dir to the directory name from where you are trying to resize the images.将 img_dir 替换为您尝试调整图像大小的目录名称。 Hope it was helpful .希望它有帮助。

This is a super late answer, but I had a lot of difficulty with this one trying to figure out why it was telling me my images were being loaded in as empty even though my path was right and none of my images were corrupted so for anyone who's here and still can't fix it: make sure you don't have .DS_Store as a file in your directory.这是一个超级晚的答案,但我在尝试弄清楚为什么它告诉我我的图像被加载为空时遇到了很多困难,即使我的路径是正确的并且我的图像没有被损坏,所以对于任何人谁在这里但仍然无法修复它:确保您的目录中没有 .DS_Store 作为文件。 If you do, it's obviously not an image file so it gets read in as empty.如果你这样做,它显然不是一个图像文件,所以它被读入为空。 Print the images and if the first image is .DS_Store, delete it: Delete .DS_STORE files in current folder and all subfolders from command line on Mac and it should work.打印图像,如果第一张图像是 .DS_Store,则将其删除: 从 Mac 上的命令行删除当前文件夹和所有子文件夹中的 .DS_STORE 文件,它应该可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM