pythonimagefor-loopgoogle-cloud-visionvision-api

How to analyze multiple images in a folder using a loop?


I am using google cloud vision api in python. I am a Python beginner. So, I am struggling to implement the content I want to analyze in Python code. It's a simple thing, but if you can help me, I'd appreciate it.

I want to do label detection in Google Cloud Vision. I've done loading a single image and implementing the code, but I want to run it on an entire folder containing multiple images.

file_name = r'img_3282615_1.jpg'
image_path = f'.\save_img\{file_name}'

with io.open(image_path, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)
response = client.label_detection(image=image, max_results=100)
labels = response.label_annotations

df = pd.DataFrame(columns=['description', 'score', 'topicality'])

for label in labels:
    df = df.append(
        dict(
            description=label.description,
            score=label.score,
            topicality=label.topicality
        ), ignore_index=True)

print(df)

I've tried analyzing individual images using this code.

Here I would like to do the following steps.

  1. Open the folder
  2. Analyze label detection for all images in the folder(The image names are 'img_3282615_1.jpg', 'img_3282615_2.jpg', 'img_3282615_3.jpg', 'img_1115368_1.jpg', 'img_1115368_2.jpg' ...)
  3. Saving the result as csv (image name, description, score)

I studied that it is possible to repeat using the for statement, but it is difficult to actually write in code. Because I'm just starting to deal with python and lack the basics.

Your answer can be of great help to me.

thank you:)


Solution

  • Can you try this:

    from google.cloud import vision
    import os
    import csv 
    
    # Create a client for the Cloud Vision API
    client = vision.ImageAnnotatorClient()
    
    # Set the path to the folder containing the images
    folder_path = './image_for_text/'
    fields = ['description', 'score', 'topicality'] 
    filename_CSV = "./z.csv"
    list1=[]
    
    
    with open(filename_CSV, 'a+') as csvfile: 
                  writer = csv.writer(csvfile)
                  writer.writerow(fields)
    
    
    # Loop through all the files in the folder
    for filename in os.listdir(folder_path):
        # Check if the file is an image
        if filename.endswith('.jpg') or filename.endswith('.png'):
            # Build the full path to the image
            file_path = os.path.join(folder_path, filename)
            # Open the image file
            with open(file_path, 'rb') as image_file:
                # Read the image file into memory
                content = image_file.read()
            
            #Create a vision image from the binary data
            image = vision.Image(content=content)
            
            #Perform label detection on the image
            response = client.label_detection(image=image)
            labels = response.label_annotations
            # Print the labels for the image
            print(f'Labels for {filename}:')
            for label in labels:
                list1.append(f'{label.description}')
                list1.append(f'{label.score*100:.2f}%')
                list1.append(f'{label.topicality}')
                print(list1)
                with open(filename_CSV, 'a+') as csvfile: 
                  writer = csv.writer(csvfile)
                  writer.writerow(list1)
                  list1.clear()