Copying Numpy Array With '=' Operator. Why Is It Working?
According to this answer, B=A
where A
is a numpy array, B
should be pointing to the same object A
.
import cv2
import numpy as np
img = cv2.imread('rose.jpeg')
print("img.shape: ", np.shape(img))
img2 = img
img = cv2.resize(img, (250,100))
print("img.shape: ", img.shape)
print("img2.shape:", img2.shape)
Output:
img.shape: (331, 500, 3)
img.shape: (100, 250, 3)
img2.shape: (331, 500, 3)
It seems to be a very basic question, but I have been scratching my head over this. Could someone please explain what's happening behind it?
Answer
The "problem" is that your not using numpy here but opencv and while numpy array.resize() is in-place opencv img.resize() is not.
So your call to
img = cv2.resize(img, (250,100))
creates a new object (image) with the given size. So here the img variable will point to a different object then before the call.
img2 = img
adds a new name for the original object. Here img2 and img are refering to exactly the same object/piece of memory.
img = cv2.resize(img, (250,100))
cv2.resize(img, (250,100))
creates a new object and the name img
now refers to that new object/piece of memory.
print("img.shape: ", img.shape)
gets you the size of the new object and
print("img2.shape:", img2.shape)
the size of the original object as img2 still refers to the original object.
By the way in numpy the call a = a.resize(...)
would be really bad - because a
would then by None
(return value of resize
) instead of the resized array. There you would just do a.resize(...)
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module