如何不使用OpenCV函数实现与给定代码一致的图像圆形绘制效果?
Replicating OpenCV Circle Drawing Without OpenCV Functions
Great question! To replicate the exact output of your OpenCV code without using any OpenCV functions, we can use NumPy for efficient image manipulation and Matplotlib for display. Here's a step-by-step breakdown and implementation:
Key Details to Match the Original Code
Your original code creates a 512×512 white image, then draws:
- A blue filled circle (BGR:
(255,0,0)) with an inner radius of 55 (since the border is 8 pixels thick, inner radius = 63 - 8) - A red border (BGR:
(0,0,255)) spanning from radius 55 to 63
We’ll use NumPy’s vectorized operations (instead of slow pixel-by-pixel loops) to efficiently calculate which pixels fall into these regions.
Full Code Implementation
import numpy as np import matplotlib.pyplot as plt # 1. Create a 512x512 white image (BGR format, matching OpenCV's default) img = np.ones((512, 512, 3), dtype=np.uint8) * 255 # 2. Define circle parameters (matches your OpenCV code) center = (256, 256) outer_radius = 63 border_thickness = 8 inner_radius = outer_radius - border_thickness # 3. Generate coordinate grids for all pixels # Using 'ij' indexing to align with image rows (y) and columns (x) y_coords, x_coords = np.meshgrid(np.arange(512), np.arange(512), indexing='ij') # 4. Calculate squared distance from each pixel to the center # Using squared distance avoids expensive square root operations for efficiency dx = x_coords - center[0] dy = y_coords - center[1] distance_squared = dx**2 + dy**2 # 5. Create masks for the fill and border regions fill_mask = distance_squared <= inner_radius**2 border_mask = (distance_squared <= outer_radius**2) & (distance_squared > inner_radius**2) # 6. Apply colors (BGR order to match OpenCV's color format) img[fill_mask] = (255, 0, 0) # Blue fill (BGR) img[border_mask] = (0, 0, 255) # Red border (BGR) # 7. Convert BGR to RGB for correct display in Matplotlib # Matplotlib uses RGB, while OpenCV uses BGR by default img_rgb = img[..., ::-1] # 8. Display the final image plt.imshow(img_rgb) plt.axis('off') # Hide axis ticks/labels for a clean, identical view plt.show()
How This Works
- Vectorized Operations: Instead of looping through every pixel (which is slow), we use NumPy’s meshgrids to compute distances for all pixels at once, making the code fast and concise.
- Masking: We create boolean masks to identify which pixels belong to the fill or border, then apply the corresponding colors in one efficient step.
- Color Format: We keep the image in BGR format to match the original OpenCV output, then convert to RGB only for display in Matplotlib (since Matplotlib expects RGB order).
This code will produce an identical image to your OpenCV version—same white background, blue fill, red border, and dimensions.
内容的提问来源于stack exchange,提问作者Casm
相关产品推荐
相关产品推荐

