[Python] Why copying the numpy array does not take the effect?

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write a simple function which will blend two images, black background and hand image, and move the hand image over the background. I managed to move the hand image over the background, but I don't know why the background does not get cleared when I reassign the original background to the temporary image (it works only when I re-declare background in helper function):

    import cv2
    import numpy as np
    import time
    import math

    SEQUENCE_LENGTH = 15

    def rotate(background, hand):
    h,w = hand.shape[:2] #Get hand shape
    step = math.floor((background.shape[1]-hand.shape[1])/SEQUENCE_LENGTH) #Calculat>

    merged = background[:] #Create temporary array for merging bckg and hand image
    #background = np.zeros((480,640,3),dtype='uint8')
    for i in range(SEQUENCE_LENGTH):
    x_offset = i*step
    y_offset = 0

    merged[y_offset:y_offset+h, x_offset:x_offset + w] = hand
    cv2.imshow("Hand", merged)
    cv2.waitKey(100)
    merged[:] = background[:] ### Why this does not take effect, unless I uncomm>
    ### background = np.zeros((480,640,3),dtype='uint8')

    def main():
    bckg = np.zeros((480,640,3),dtype='uint8') #Generate black background
    hand = cv2.imread("/home/hand.jpg") # Get hand image
    # Define new width and height
    new_width = 100
    new_height = 100

    resized_hand = cv2.resize(hand, (new_width, new_height)) #Resize hand image
    rotate(bckg,resized_hand) #Call rotation function
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    if __name__ == "__main__":
    main()


    The background gets cleared only when I re-declare background=np.zeros((480,640,3),dtype='uint8'). Otherwise I see the remaining of previous hand image in the background:

    No remainings: [​IMG]

    Clear background: [​IMG]

    It looks like the background assignment does not work, the question is why? I checked the datatypes of background and merged image, and they are the same regardless of whether I use the np.zeros assignment or not.

    Continue reading...

Compartilhe esta Página