1
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

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

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

Zhubei Federer
  • 1,274
  • 2
  • 10
  • 27

4 Answers4

1

I got this error today because my path of images was not right.U can try to show one image to see whether you read the image successfully.

Rhapsody
  • 43
  • 1
  • 1
  • 7
0

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.

0

Just type this your script or ipython cell to verify if there is an empty or corrupt image that might create this error .

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. Hope it was helpful .

Ajay Alex
  • 473
  • 4
  • 7
0

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. 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.

quibbles
  • 23
  • 4