give me a python script to draw bounding box to a picture in given image based on…
- User
give me a python script to draw bounding box to a picture in given image based on coordiantes, the script should ask user for coordiantes and image path
- Assistant
Certainly! Below is a Python script that allows you to draw a bounding box on an image based on user-provided coordinates and image path. The script uses the OpenCV library (
opencv-python) to handle image processing tasks.
Prerequisites
-
Python Installation: Ensure you have Python 3.x installed on your system. You can download it from the official website.
-
Install OpenCV: You need to install the OpenCV library. You can install it using
pip:pip install opencv-pythonIf you're using Jupyter Notebook or another environment, make sure the OpenCV library is installed in the correct environment.
Python Script
import cv2 import os def get_image_path(): """ Prompt the user to enter the image path and verify its existence. """ while True: image_path = input("Enter the path to the image: ").strip() if os.path.isfile(image_path): return image_path else: print("File does not exist. Please enter a valid file path.") def get_coordinates(): """ Prompt the user to enter the bounding box coordinates. Ensures that the coordinates are integers and that (x1, y1) is the top-left and (x2, y2) is the bottom-right corner. """ while True: try: print("\nEnter the bounding box coordinates:") x1 = int(input(" Top-left x: ")) y1 = int(input(" Top-left y: ")) x2 = int(input(" Bottom-right x: ")) y2 = int(input(" Bottom-right y: ")) if x1 < x2 and y1 < y2: return (x1, y1, x2, y2) else: print(" Error: Top-left coordinates must be less than bottom-right coordinates.") except ValueError: print(" Error: Please enter valid integer values for coordinates.") def draw_bounding_box(image_path, coords): """ Draws a bounding box on the image using the provided coordinates and displays/saves the result. """ # Read the image image = cv2.imread(image_path) if image is None: print("Error: Could not read the image. Please check the file path and format.") return height, width, _ = image.shape x1, y1, x2, y2 = coords # Validate coordinates against image dimensions if not (0 <= x1 < x2 <= width) or not (0 <= y1 < y2 <= height): print("Error: Coordinates are out of image bounds.") print(f"Image dimensions: width={width}, height={height}") return # Draw the bounding box # Parameters: image, start_point, end_point, color (BGR), thickness cv2.rectangle(image, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=2) # Display the image with the bounding box cv2.imshow("Image with Bounding Box", image) print("\nPress any key in the image window to close it.") cv2.waitKey(0) cv2.destroyAllWindows() # Save the new image with a bounding box base, ext = os.path.splitext(image_path) output_path = f"{base}_boxed{ext}" success = cv2.imwrite(output_path, image) if success: print(f"Image with bounding box saved as: {output_path}") else: print("Error: Could not save the image.") def main(): """ Main function to orchestrate the bounding box drawing process. """ print("=== Bounding Box Drawer ===\n") image_path = get_image_path() coords = get_coordinates() draw_bounding_box(image_path, coords) if __name__ == "__main__": main()
How the Script Works
-
Import Libraries:
cv2: OpenCV library for image processing.os: For file path operations.
-
Function
get_image_path():- Prompts the user to input the image file path.
- Validates the existence of the file. If the file doesn't exist, it prompts the user again.
-
Function
get_coordinates():- Prompts the user to input the bounding box coordinates:
- Top-left x (
x1) - Top-left y (
y1) - Bottom-right x (
x2) - Bottom-right y (
y2)
- Top-left x (
- Ensures that:
- All inputs are integers.
x1 < x2andy1 < y2to define a valid rectangle.
- If invalid inputs are provided, it prompts the user again.
- Prompts the user to input the bounding box coordinates:
-
Function
draw_bounding_box(image_path, coords):- Reads the Image: Uses
cv2.imreadto load the image. - Validates Coordinates: Ensures that the provided bounding box coordinates are within the image dimensions.
- Draws the Rectangle:
- Uses
cv2.rectangleto draw the bounding box. - Color is set to red
(0, 0, 255)in BGR format. - Thickness is set to
2pixels.
- Uses
- Displays the Image: Shows the image with the bounding box in a new window.
- Saves the Modified Image:
- Appends
_boxedto the original filename before the file extension. - Saves the image using
cv2.imwrite.
- Appends
- Reads the Image: Uses
-
Function
main():- Orchestrates the flow by calling the above functions in sequence.
-
Script Execution:
- The script starts executing from the
main()function when run directly.
- The script starts executing from the
Running the Script
-
Save the Script: Save the above script to a file, for example,
draw_bounding_box.py. -
Prepare an Image: Ensure you have an image file (e.g.,
sample.jpg) in a known directory. -
Execute the Script:
Open a terminal or command prompt, navigate to the directory containing
draw_bounding_box.py, and run:python draw_bounding_box.py -
Provide Inputs:
- Image Path: Enter the full path to your image. For example:
Enter the path to the image: /path/to/your/image/sample.jpg - Coordinates:
Enter the bounding box coordinates: Top-left x: 50 Top-left y: 100 Bottom-right x: 200 Bottom-right y: 300
- Image Path: Enter the full path to your image. For example:
-
View and Save:
- An image window will pop up displaying the image with the bounding box.
- Press any key while the image window is focused to close it.
- The modified image will be saved in the same directory as the original image with
_boxedappended to its name, e.g.,sample_boxed.jpg.
Example Run
=== Bounding Box Drawer === Enter the path to the image: /Users/username/Pictures/sample.jpg Enter the bounding box coordinates: Top-left x: 50 Top-left y: 100 Bottom-right x: 200 Bottom-right y: 300 Press any key in the image window to close it. Image with bounding box saved as: /Users/username/Pictures/sample_boxed.jpg
Notes & Tips
-
Coordinate System: In image processing, the coordinate system starts at the top-left corner of the image. The x-axis extends to the right, and the y-axis extends downward.
-
Valid Coordinates: Ensure that the coordinates you provide are within the image dimensions to avoid errors. For example, if your image is 400x400 pixels, both
xandycoordinates should be between0and400. -
Color Specification: OpenCV uses BGR (Blue, Green, Red) color format by default. The script uses red
(0, 0, 255)for the bounding box, but you can change it by modifying thecolorparameter in thecv2.rectanglefunction. -
Thickness: The
thicknessparameter incv2.rectangledetermines how thick the bounding box lines will be. A value of-1will fill the rectangle. -
Handling Different Image Formats: OpenCV supports various image formats like
.jpg,.png,.bmp, etc. Ensure that the file extension matches the actual image format. -
Error Handling: The script includes basic error handling for invalid file paths and coordinate inputs. You can enhance it further based on your requirements.
Feel free to customize and extend this script according to your needs, such as adding multiple bounding boxes, selecting colors dynamically, or integrating with a graphical user interface (GUI).
-