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:
img1 = img.copy()
This line creates a new independent copy of theimg
object and assigns it to the variableimg1
. Thecopy()
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 modifyingimg1
will not affect the originalimg
object. They are separate instances in memory.img1 = img
This line assigns the reference of theimg
object to the variableimg1
. In other words, bothimg
andimg1
now point to the same image object in memory. This means that any modifications made toimg1
will directly affect the originalimg
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)

#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)

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.