多次克隆 NumPy 数组

Clone a NumPy array multiple times(多次克隆 NumPy 数组)
本文介绍了多次克隆 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-

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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)