Difference between img1=img.copy() and img1 = img!

poonam
2 min readJun 12, 2023

The difference between img1 = img.copy() and img1 = img lies in how the assignment is made and the resulting behavior. Let's break it down:

  1. img1 = img.copy() This line creates a new independent copy of the img object and assigns it to the variable img1. The copy() method is typically used to create a deep copy of an object. In the context of an image, it creates a new image object with the same pixel values as the original image. The key point here is that modifying img1 will not affect the original img object. They are separate instances in memory.
  2. img1 = img This line assigns the reference of the img object to the variable img1. In other words, both img and img1 now point to the same image object in memory. This means that any modifications made to img1 will directly affect the original img object as well. They essentially become two different names for the same underlying object.

Let's pick an example,

import cv2
import numpy as np

#Read Image
img = cv2.imread("./Data/dataset1/0.bmp")
#image channel work
img1=img
img1[:,:,0] = 0 #modify copy of image

img_new = np.hstack((img, img1))
cv2.imshow("WindowImageCopy", img_new)
cv2.waitKey(0)
The original image is shown on the left half and the new image img1 is on the right half. Results of img1=img
#image channel work
img1=img.copy()
img1[:,:,0] = 0 #modify copy of image

img_new = np.hstack((img, img1))
cv2.imshow("WindowImageCopy", img_new)
cv2.waitKey(0)
The original image is shown on the left half and the new image img1 is on the right half. Results of img1=img.copy()

In summary, when you use img1 = img.copy(), you create a new copy of the image, allowing you to modify img1 independently. However, when you use img1 = img, both variables refer to the same image object, so any changes made through img1 will be reflected in img as well.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

poonam
poonam

Written by poonam

An Engineer and philosopher

No responses yet

Write a response