shivam1808 / Object_Detection

Create your own custom object detector using the Tensorflow Object Detection API.
1 stars 0 forks source link

Testing Images in Folder #1

Open Annieliaquat opened 2 years ago

Annieliaquat commented 2 years ago

I am using Tensorflow object detection Api. I have completed training and have download the trained model through "Python export_v2.py " code. Now I want to test my model on my test Images folder. There are many codes that can read and detect single image. But I want to detect my all 50 images that are on my folder. Kinldy please help me do that.. Thanks in advance

shivam1808 commented 2 years ago

You can using the concept of File Handling (os library) in Python.

# Import OS module
import os

path = "C://Users//Shivam//Desktop//Test"

# Get list of all the Images  in Test folder
dir_list = os.listdir(path)

# Iterate all the Images in Test folder
for x in os.listdir():
    print("File name: " + x)
    os.system("<Command to execute your python script>")

# Note1: Pass the Image as an runtime arguement so that you can append the Image name with the above command.
# Example: python3 python_script.py file_name.jpg

#Note2: Dynamically update the output file name otherwise output of every image will overwrite.
Annieliaquat commented 2 years ago

You can using the concept of File Handling (os library) in Python.


# Import OS module
import os

path = "C://Users//Shivam//Desktop//Test"

# Get list of all the Images  in Test folder
dir_list = os.listdir(path)

# Iterate all the Images in Test folder
for x in os.listdir():
    print("File name: " + x)
    os.system("<Command to execute your python script>")

# Note1: Pass the Image as an runtime arguement so that you can append the Image name with the above command.
# Example: python3 python_script.py file_name.jpg

#Note2: Dynamically update the output file name otherwise output of every image will overwrite.

Will this work on google colab?
Annieliaquat commented 2 years ago

You can using the concept of File Handling (os library) in Python.

# Import OS module
import os

path = "C://Users//Shivam//Desktop//Test"

# Get list of all the Images  in Test folder
dir_list = os.listdir(path)

# Iterate all the Images in Test folder
for x in os.listdir():
    print("File name: " + x)
    os.system("<Command to execute your python script>")

# Note1: Pass the Image as an runtime arguement so that you can append the Image name with the above command.
# Example: python3 python_script.py file_name.jpg

#Note2: Dynamically update the output file name otherwise output of every image will overwrite.

IMAGE_PATH = os.path.join(paths['IMAGE_PATH'], 'test', 'livelong.02533422-940e-11eb-9dbd-5cf3709bbcc6.jpg')

img = cv2.imread(IMAGE_PATH) image_np = np.array(img)

input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32) detections = detect_fn(input_tensor)

num_detections = int(detections.pop('num_detections')) detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()} detections['num_detections'] = num_detections

detection_classes should be ints.

detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

label_id_offset = 1 image_np_with_detections = image_np.copy()

viz_utils.visualize_boxes_and_labels_on_image_array( image_np_with_detections, detections['detection_boxes'], detections['detection_classes']+label_id_offset, detections['detection_scores'], category_index, use_normalized_coordinates=True, max_boxes_to_draw=5, min_score_thresh=.8, agnostic_mode=False)

plt.imshow(cv2.cvtColor(image_np_with_detections, cv2.COLOR_BGR2RGB)) plt.show()

As this code is used for detecting single image. How can I use this for my folder which has 50 images.

shivam1808 commented 2 years ago
# Import OS module
import os

path = "test"

# Get list of all the Images  in Test folder
dir_list = os.listdir(path)

# Iterate all the Images in Test folder
for x in os.listdir():
    print("File name: " + x)
    image_detection(x)

def image_detection(name):

    IMAGE_PATH = os.path.join(paths['IMAGE_PATH'], 'test', name)

    img = cv2.imread(IMAGE_PATH)
    image_np = np.array(img)

    input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
    detections = detect_fn(input_tensor)

    num_detections = int(detections.pop('num_detections'))
    detections = {key: value[0, :num_detections].numpy()
    for key, value in detections.items()}
    detections['num_detections'] = num_detections

    detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

    label_id_offset = 1
    image_np_with_detections = image_np.copy()

    viz_utils.visualize_boxes_and_labels_on_image_array(
                                            image_np_with_detections,
                                            detections['detection_boxes'],
                                            detections['detection_classes']+label_id_offset,
                                            detections['detection_scores'],
                                            category_index,
                                            use_normalized_coordinates=True,
                                            max_boxes_to_draw=5,
                                            min_score_thresh=.8,
                                            agnostic_mode=False)

    plt.imshow(cv2.cvtColor(image_np_with_detections, cv2.COLOR_BGR2RGB))
    plt.show()

Check if this will work and make required changes with respect to path.

Annieliaquat commented 2 years ago

what is the name argument here?? I will try this code. if it doesnot work, I will let you know

shivam1808 commented 2 years ago

name argument is the image file name.

Annieliaquat commented 2 years ago

name argument is the image file name.

I am confuse on how to provide path to the code you have type. like my folder path is "/content/drive/MyDrive/DetectionApi/workspace/images/test" image Should I give the full path here? If yes then what should I write here image bcz the path is conflicting with each other . Kindly guide me image

Annieliaquat commented 2 years ago

name argument is the image file name.

Please guide me on how to provide file paths properly. What should be written in Image_Path and what should I write in path ?

shivam1808 commented 2 years ago

Please guide me on how to provide file paths properly. What should be written in Image_Path and what should I write in path ?

"Path" variable should be your folder path. i.e., path = "/content/drive/MyDrive/DetectionApi/workspace/images/test" Remove the IMAGE_PATH line.

Make below changes:

Change1 -> img = cv2.imread(name)

Change 2 in the loop -> image_detection(path+x)

After making all the changes try to run.

Annieliaquat commented 2 years ago

Please guide me on how to provide file paths properly. What should be written in Image_Path and what should I write in path ?

"Path" variable should be your folder path. i.e., path = "/content/drive/MyDrive/DetectionApi/workspace/images/test" Remove the IMAGE_PATH line.

Make below changes:

Change1 -> img = cv2.imread(name)

Change 2 in the loop -> image_detection(path+x)

After making all the changes try to run.

(Path+x) is giving me error

Annieliaquat commented 2 years ago

As this is the code for giving image path for single image IMAGE_PATH =os.path.join(IMAGE_PATH, 'test', 'NORMAL-5661793-0001.jpeg')

This is the code for detection function configs = config_util.get_configs_from_pipeline_file(CONFIG_PATH) detection_model = model_builder.build(model_config=configs['model'], is_training=False)

Restore checkpoint

ckpt = tf.compat.v2.train.Checkpoint(model=detection_model) ckpt.restore(os.path.join(CHECKPOINT_PATH, 'ckpt-6')).expect_partial()

@tf.function def detect_fn(image): image, shapes = detection_model.preprocess(image) prediction_dict = detection_model.predict(image, shapes) detections = detection_model.postprocess(prediction_dict, shapes) return detections

This is the code for reading image . img = cv2.imread(IMAGE_PATH) image_np = np.array(img)

input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32) detections = detect_fn(input_tensor)

num_detections = int(detections.pop('num_detections')) detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()} detections['num_detections'] = num_detections

detection_classes should be ints.

detections['detection_classes'] = detections['detection_classes'].astype(np.int64)

label_id_offset = 1 image_np_with_detections = image_np.copy()

viz_utils.visualize_boxes_and_labels_on_image_array( image_np_with_detections, detections['detection_boxes'], detections['detection_classes']+label_id_offset, detections['detection_scores'], category_index, use_normalized_coordinates=True, max_boxes_to_draw=3, min_score_thresh=.4, agnostic_mode=False)

plt.imshow(cv2.cvtColor(image_np_with_detections, cv2.COLOR_BGR2RGB)) plt.show()

Considering this code can you just guide me on how to run this for the complete folder.

Actually I have used tensorflow object detection api for training a model. After successful training, I have evaluate my model so it is giving me mAP and loss. But I want my model to show accuracy but it is not. So now, for finding accuracy, I don't have other way to find it. So I am thinking of finding accuracy by detecting all images in my folder, and then use the formula to find accuracy

shivam1808 commented 2 years ago

Can we connect to check the error you are facing? Mail Id: shivamguptasg1808@gmail.com

Annieliaquat commented 2 years ago

Can we connect to check the error you are facing? Mail Id: shivamguptasg1808@gmail.com

Yes sure I will send you email tomorrow