Sub topic 13
Drawing on a Copy to Keep the Original Intact
This chapter assumes you can read an image with cv2.imread, index NumPy arrays, and use the drawing functions cv2.line, cv2.rectangle, cv2.circle, and cv2.putText. It also assumes you know that OpenCV images are uint8 arrays in BGR order. The chapter explains why drawing changes your data, how to avoid that, and the cases where a plain .copy() is still not enough.
Drawing modifies the array in place
Every OpenCV drawing function writes into the array you pass it. It does not build a new image. The function also returns that same array, which makes it easy to believe a new image was created.
import cv2
import numpy as np
img = np.full((200, 300, 3), 255, dtype=np.uint8) # a white image
canvas = img # this is a second name for the same array, not a copy
result = cv2.rectangle(canvas, (20, 20), (120, 100), (0, 0, 255), 2)
print(canvas is img) # True
print(result is img) # True
print(img[20, 20].tolist()) # [0, 0, 255]: the "original" now has a red cornerThe assignment canvas = img copies a reference, not pixels. The call to cv2.rectangle changed the one array that all three names point to. If you later save img expecting a clean image, the rectangle is in the file.
A drawing call can also fail to give you a fresh result because of a habit from other libraries. In Pillow, ImageDraw also draws in place, but many NumPy and OpenCV functions such as cv2.resize and cv2.cvtColor do return new arrays. Drawing functions are the exception, so check each function you use.
Making a real copy
ndarray.copy() allocates new memory and duplicates every pixel. Drawing on the duplicate leaves the original untouched.
import cv2
import numpy as np
img = np.full((200, 300, 3), 255, dtype=np.uint8)
annotated = img.copy()
cv2.rectangle(annotated, (20, 20), (120, 100), (0, 0, 255), 2)
print(np.array_equal(img, annotated)) # False: the copy has the rectangle
print(int(img.min())) # 255: the original is still all white
print(np.shares_memory(img, annotated)) # False: independent buffersnp.shares_memory(a, b) is the most direct check for aliasing. Use it when you are unsure whether two names refer to the same pixels. The is operator is less reliable: two different array objects can still share memory, as the next section shows.
The following diagram shows the pattern.
Views, slices, and what counts as a copy
The chapter on cropping showed that a slice like img[50:200, 100:300] is a view. It shares memory with the source array. Drawing on a view therefore draws on the original.
import cv2
import numpy as np
img = np.full((200, 300, 3), 255, dtype=np.uint8)
roi = img[50:150, 100:200] # a view
print(np.shares_memory(img, roi)) # True
# Coordinates are relative to the ROI, not to the full image
cv2.circle(roi, (50, 50), 20, (255, 0, 0), -1)
# The ROI's (50, 50) is the original's x=150, y=100
print(img[100, 150].tolist()) # [255, 0, 0]This is sometimes what you want: you can draw inside a region using local coordinates. Remember that the ROI has its own origin, so point (50, 50) in the ROI is (150, 100) in the full image. If you want an independent crop, call .copy() on it.
| Expression | New pixel memory? | Drawing affects the original? |
|---|---|---|
| `canvas = img` | No | Yes |
| `canvas = img[:]` | No | Yes |
| `roi = img[y1:y2, x1:x2]` | No | Yes |
| `canvas = img.copy()` | Yes | No |
| `canvas = np.copy(img)` | Yes | No |
| `roi = img[y1:y2, x1:x2].copy()` | Yes | No |
| `gray = cv2.cvtColor(img, ...)` | Yes | No |
Functions such as cv2.resize and cv2.cvtColor return new arrays, so drawing on their results is safe. Even so, an explicit .copy() before drawing makes your intent obvious to anyone reading the code.
Put the copy inside a function
The most reliable way to avoid accidental mutation is to make the copy in one place. A function takes an image, copies it, draws, and returns the copy. Callers cannot forget the copy because they never draw directly.
import cv2
import numpy as np
def annotate(image, boxes, labels, color=(0, 255, 0)):
"""Return a new image with labeled boxes. The input is not modified."""
out = image.copy()
for (x1, y1, x2, y2), label in zip(boxes, labels):
cv2.rectangle(out, (x1, y1), (x2, y2), color, 2)
# Keep the label inside the image when the box touches the top edge
text_y = max(y1 - 6, 14)
cv2.putText(out, label, (x1, text_y), cv2.FONT_HERSHEY_SIMPLEX,
0.5, color, 1, cv2.LINE_AA)
return out
img = np.zeros((240, 320, 3), dtype=np.uint8)
before = img.copy()
boxes = [(30, 40, 150, 120), (180, 60, 290, 200)]
labels = ["cat", "dog"]
result = annotate(img, boxes, labels)
print(np.array_equal(img, before)) # True: input untouched
print(np.array_equal(img, result)) # False: output has the drawings
cv2.imwrite("annotated.png", result)Two details in this function matter.
- The copy happens once per call, not once per box. Copying inside the loop would discard the earlier boxes, because each iteration would start again from the clean image.
- Every shape is drawn on
out, never onimage. A single straycv2.rectangle(image, ...)would silently break the guarantee.
Keeping a clean version alongside the annotated one
A common workflow needs both versions: the raw frame for saving or further processing, and an annotated frame for display. Make the copy at the moment you branch.
import cv2
cap = cv2.VideoCapture(0)
ok, frame = cap.read()
cap.release()
if not ok:
raise RuntimeError("Could not read a frame from the camera")
display = frame.copy()
h, w = frame.shape[:2]
cv2.putText(display, f"{w}x{h}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
1, (0, 255, 255), 2, cv2.LINE_AA)
cv2.imwrite("raw_frame.png", frame) # clean pixels
cv2.imwrite("display_frame.png", display) # with textIf you only show the frame and never reuse it, the copy is unnecessary. Each call to cap.read() returns fresh data, so there is nothing to protect. Copy when two parts of the program need different versions of the same pixels.
Cost of copying
A copy is a full memory duplication. A 4000 by 3000 pixel BGR image occupies 4000 × 3000 × 3 = 36,000,000 bytes, about 34 MiB. One copy per image is cheap. A copy per drawn shape across thousands of images wastes time and memory. Copy once per annotated output, and draw all shapes on that one canvas.
For video at a high frame rate, you can reuse one preallocated buffer instead of allocating a new array for each frame. Do this with np.copyto(canvas, frame), which overwrites the existing pixels in place:
import cv2
import numpy as np
frame = np.zeros((480, 640, 3), dtype=np.uint8)
canvas = np.empty_like(frame)
for i in range(3):
np.copyto(canvas, frame) # reset canvas to the clean frame, no new allocation
cv2.circle(canvas, (100 + i * 50, 240), 30, (0, 255, 0), -1)
# show or save canvas hereMeasure before adopting this. For still images, .copy() is simpler and fast enough.
Edge cases and failure modes
- Drawing on a stepped view. A view that skips pixels or selects one channel, such as
img[:, ::2]orimg[:, :, 0], is not laid out the way OpenCV expects. Drawing on it typically raises acv2.errorabout an incompatible array layout. Call.copy()first, which produces a contiguous array. Plain row and column crops likeimg[50:200, 100:300]work fine. - Grayscale canvases. On a 2D image, the color argument is read as a single intensity. A tuple like
(0, 0, 255)draws with only its first value,0, which is black. Convert to BGR withcv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)before drawing colored annotations. - Wrong dtype. Drawing assumes
uint8values from 0 to 255. If you converted an image tofloat32for processing, scale it back before annotating, or colors will not look as expected. - Drawing then cropping. If you crop from the annotated canvas instead of the original, the crop contains your lines and text. Take crops from the clean image.
- Accumulating drawings in a loop. If you redraw each frame on the same canvas without resetting it, old shapes pile up. Reset with a fresh
.copy()ornp.copytoat the start of every iteration. - Relying on the return value.
canvas = cv2.rectangle(canvas, ...)works, but it does not copy anything. The return value is the same object you passed in.
Looking ahead
The semi-transparent overlay technique in the next chapter depends on exactly this pattern. It draws a filled shape on one copy, then blends that copy with the untouched original using cv2.addWeighted. Without a clean original to blend against, there would be nothing to make the shape transparent over.
Exercise
You run this code and then save img to disk. The saved file contains a green line. Why, and what is the smallest change that keeps img clean?
img = cv2.imread("photo.jpg")
view = img[0:100, :]
cv2.line(view, (0, 0), (50, 50), (0, 255, 0), 2)
cv2.imwrite("clean.png", img)
Show answer
img[0:100, :] is a slice, so view is a view that shares memory with img. cv2.line draws in place on that shared memory, so img changes. The smallest fix is to copy the slice before drawing: view = img[0:100, :].copy(). If you want an annotated full image, copy the whole image first with canvas = img.copy() and draw on canvas.
Exercise
Write a function mark_points(image, points) that returns a new image with a filled red circle of radius 5 at each (x, y) in points. The input image must not change. Then explain how you would check that it did not change.
Show answer
def markpoints(image, points):
out = image.copy()
for x, y in points:
cv2.circle(out, (x, y), 5, (0, 0, 255), -1)
return out
To check, save a reference copy before the call, before = img.copy(), and afterward confirm `np.arrayequal(img, before) is True. Also confirm np.shares_memory(img, result) is False`. The copy is made once outside the loop so all circles appear on the same output.
Exercise
A loop draws one rectangle per frame, but the output video shows the rectangles from all earlier frames at once. What went wrong, and how do you fix it without allocating a new array every frame?
Show answer
The same canvas array is reused and never reset, so each frame's drawing is added to the previous ones. Reset it at the start of each iteration. Use canvas = frame.copy() for simplicity, or preallocate canvas = np.empty_like(frame) once and call np.copyto(canvas, frame) at the start of every iteration to avoid a new allocation.