Как нарисовать круг на изображении с помощью Python: методы OpenCV, PIL и Matplotlib

Вот несколько способов нарисовать круг на изображении с помощью Python:

Метод 1: использование OpenCV

import cv2
import numpy as np
# Load the image
image = cv2.imread('image.jpg')
# Get the image dimensions
height, width, _ = image.shape
# Calculate the center and radius of the circle
center = (int(width/2), int(height/2))
radius = min(center[0], center[1])
# Draw the circle on the image
cv2.circle(image, center, radius, (0, 255, 0), 2)
# Display the image
cv2.imshow('Circle on Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Метод 2: использование PIL (библиотеки изображений Python)

from PIL import Image, ImageDraw
# Load the image
image = Image.open('image.jpg')
# Create a new image with transparency
circle_image = Image.new('RGBA', image.size, (0, 0, 0, 0))
# Draw the circle on the new image
draw = ImageDraw.Draw(circle_image)
draw.ellipse([(center[0]-radius, center[1]-radius), (center[0]+radius, center[1]+radius)], outline=(0, 255, 0), width=2)
# Composite the original image with the circle image
result = Image.alpha_composite(image.convert('RGBA'), circle_image)
# Display the image
result.show()

Метод 3: использование Matplotlib

import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
# Load the image
image = Image.open('image.jpg')
# Create a figure and axes
fig, ax = plt.subplots()
# Display the image
ax.imshow(image)
# Create a circle patch
circle = patches.Circle(center, radius, edgecolor='g', linewidth=2, facecolor='none')
# Add the circle patch to the axes
ax.add_patch(circle)
# Show the plot
plt.show()