Sub topic 13
Drawing on a Copy to Keep the Original Intact
This chapter assumes basic Python, NumPy array indexing, and OpenCV image loading. You should know that an OpenCV image is a NumPy array. The array is mutable, which means drawing operations can change its contents directly.
Why copies matter
OpenCV drawing functions such as cv2.line, cv2.rectangle, and cv2.putText modify the image array in place. If you draw directly on the array returned by cv2.imread, the original image data changes.
Use .copy() when you need an annotated version while preserving the original:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
annotated = img.copy()
cv2.rectangle(
annotated,
(50, 50),
(250, 200),
(0, 255, 0),
2,
)
cv2.putText(
annotated,
"Object",
(50, 40),
cv2.FONT_HERSHEY_SIMPLEX,
1,
(0, 255, 0),
2,
cv2.LINE_AA,
)
cv2.imwrite("annotated.jpg", annotated)
cv2.imwrite("original_copy.jpg", img)The img array remains unchanged. The drawing appears only in annotated.
Crops and views
NumPy slicing usually returns a view, not a separate array. A view shares data with its source:
roi = img[50:200, 100:300]Drawing on roi can therefore change the matching area in img. Use .copy() when the crop must be independent:
roi = img[50:200, 100:300].copy()
cv2.circle(roi, (75, 50), 25, (0, 0, 255), 2)Coordinates inside this crop start at (0, 0), even though the crop begins at (100, 50) in the original image.
A safe drawing workflow
Keep the original image and its drawing canvas separate:
flowchart TD
A[Read image into img] --> B[Create canvas with img.copy()]
B --> C[Draw shapes and labels on canvas]
C --> D[Save or display canvas]
A --> E[Use unchanged img for later processing]The img array is the source. The canvas array is the working result. This separation is useful when you need to compare the annotated image with the source, run another algorithm on the unmodified pixels, or produce multiple annotation versions.
Drawing overlays
For a filled highlight, draw on a separate overlay and blend it with the original. cv2.addWeighted combines corresponding pixels:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
overlay = img.copy()
cv2.rectangle(overlay, (50, 50), (250, 200), (0, 255, 0), -1)
alpha = 0.4
blended = cv2.addWeighted(
overlay,
alpha,
img,
1 - alpha,
0,
)
cv2.imwrite("highlighted.jpg", blended)Here, alpha controls the strength of the overlay. A value of 0.4 gives the original image a visible but partly transparent green region. The original img is still unchanged.
Exercise
Why can drawing on img[50:200, 100:300] change the original image, and how do you prevent that?
Show answer
The slice is usually a NumPy view that shares data with img. Add .copy() to make independent data before drawing.