多次克隆NumPy数组 [英] Clone a NumPy array multiple times

查看:86
本文介绍了多次克隆NumPy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将图片加载到numpy数组中,需要将图片的阈值设置为2个不同的阈值.

I loaded a picture into a numpy array and need to threshold it picture at 2 different thresholds.

import numpy as np
import cv2

cap = cv2.Videocapture(0)
_,pic = cap.read()
pic1 = pic
pic2 = pic

pic1[pic1 > 100] = 255
pic2[pic2 > 200] = 255

当我只希望他们修改pic1和pic2时,此代码将始终编辑pic

This code will always edit pic when I only want them to modify pic1 and pic2

推荐答案

在python中,对象和变量之间存在区别.变量是分配给对象的名称.一个对象在内存中可以有多个名称.

In python, there is a difference between an object and a variable. A variable is name assigned to an object; and an object can have more than one name in memory.

通过执行pic1 = pic; pic2 = pic,您将 same 对象分配给多个不同的变量名称,因此最终修改了同一对象.

By doing pic1 = pic; pic2 = pic, You're assigning the same object to multiple different variable names, so you end up modifying the same object.

您想要的是使用np.ndarray.copy创建副本.

What you want is to create copies using np.ndarray.copy

pic1 = pic.copy()
pic2 = pic.copy()

或者,非常相似地,使用np.copy

Or, quite similarly, using np.copy

pic1, pic2 = map(np.copy, (pic, pic))

实际上,此语法使确实易于克隆pic多次,具体操作如下:

This syntax actually makes it really easy to clone pic as many times as you like:

pic1, pic2, ... picN = map(np.copy, [pic] * N)

其中N是要创建的副本数.

Where N is the number of copies you want to create.

这篇关于多次克隆NumPy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆