Python Forum
changing code to work on a batch of images within a folder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
changing code to work on a batch of images within a folder
#1
Hello all,

I am currently using the code below to use a trained image classifier model to identify an image. while this all works fine it currently can only identify one image at a time and it can't save the image when it displays.

I have 800 images to identify so I am trying to figure out how to automate this.

I'm not sure if #1 I would need to add a line to this script itself. line 30 brings forth a single image but not sure on the command on how to read all images from within a folder one after the other


or make a separate script that calls this script to work on a batch of images within a folder one after the other once the original script has run on a singer image

so I was wondering if anyone could help me with this or show me some examples with something similar.

thank you in advanced.


# Import packages import os import cv2 import numpy as np import tensorflow as tf import sys # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util # Name of the directory containing the object detection module we're using MODEL_NAME = 'inference_graph' IMAGE_NAME = 'test1.jpg' # Grab path to current working directory CWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which contains the model that is used # for object detection. PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb') # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt') # Path to image PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) # Number of classes the object detector can identify NUM_CLASSES = 6 # Load the label map. # Label maps map indices to category names, so that when our convolution # network predicts `5`, we know that this corresponds to `king`. # Here we use internal utility functions, but anything that returns a # dictionary mapping integers to appropriate string labels would be fine label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') sess = tf.Session(graph=detection_graph) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detected num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Load image using OpenCV and # expand image dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value image = cv2.imread(PATH_TO_IMAGE) image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image_expanded = np.expand_dims(image_rgb, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visulaize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8, min_score_thresh=0.60) # All the results have been drawn on image. Now display the image. cv2.imshow('Object detector', image) # Press any key to close the image cv2.waitKey(0) # Clean up cv2.destroyAllWindows()
Reply
#2
you can use pathlib to get a list of images in your directory, than work on them in a for loop
An example that you can modify for your specific needs (untested, but should be OK):
from pathlib import Path ... def get_file_list(filepath): pl_path = Path(filepath) return [filename for filename in pl_path.iterdir() if filename.is_file()] filelist = get_file_list(CWD_PATH) for imagename in filelist: print(imagename.resolve())
Reply
#3
Hey, great thanks! This seems like what I am looking for. ill let you know how I get on with it. Smile
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Looping through each images in a give folder Python druva 1 2,423 Jan-01-2025, 08:46 AM
Last Post: Pedroski55
  Can't get graph code to work properly. KDDDC2DS 1 1,178 Sep-16-2024, 09:17 PM
Last Post: deanhystad
  I can't for the life of me get this basic If statement code to work CandleType1a 8 3,298 May-21-2024, 03:58 PM
Last Post: CandleType1a
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 2,165 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  hi need help to make this code work correctly atulkul1985 5 2,801 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 2,122 Oct-22-2023, 09:08 PM
Last Post: tronic72
  how do I open two instances of visual studio code with the same folder? SuchUmami 3 7,647 Jun-26-2023, 09:40 AM
Last Post: snippsat
  Beginner: Code not work when longer list raiviscoding 2 2,319 May-19-2023, 11:19 AM
Last Post: deanhystad
  Why doesn't this code work? What is wrong with path? Melcu54 7 5,125 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  Code used to work 100%, now sometimes works! muzicman0 5 3,580 Jan-13-2023, 05:09 PM
Last Post: muzicman0

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.