简体   繁体   English

np.ones 更改为元组,并且 np.asarray 没有修复它

[英]np.ones changes to a tuple and np.asarray doesn't fix it

I am making a function that masks the text out of an image using OpenCV 3.6 and I have an error where my masked array gets converted to a tuple when used in my function我正在制作一个 function,它使用 OpenCV 3.6 从图像中屏蔽文本,并且在我的function中使用时,我的masked数组被转换为元组时出现错误

my scripts look something like this with I removed the parts where I get the coordinates.我的脚本看起来像这样,我删除了获得坐标的部分。 in a for loop, I want to mask the text out of the original image.在 for 循环中,我想从原始图像中屏蔽文本。

import cv2
import numpy as np

results = [(200, 200, 300, 300), (600, 500, 1000, 900)]

def function(image, *mask):
   for(x1, y1, x2, y2) in results:
      mask[y1:y2, x1:x2] = image[y1:y2, x1:x2]
   return mask

image = cv2.imread('black.png')
masked = np.ones(image.shape, dtype=np.uint8) * 255
maskedText = function(image, masked)

cv2.imwrite("maskedText.png",maskedText)

my masked array looks normal like this:我的蒙面数组看起来很正常,如下所示:

[[[255 255 255]
[255 255 255]
[255 255 255]
...
[255 255 255]
[255 255 255]
[255 255 255]]]

but when i use mask in function it is a tuple so it doesnt work when masking with the original image and when i print it looks like this:但是当我在function中使用mask时,它是一个元组,因此在使用原始图像进行掩码时它不起作用并且当我打印时它看起来像这样:

(array([[[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255],
        ...,
        [255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]]], dtype=uint8),)

np.asarray() doesnt fix it, it just stays how it is and i keep getting the error: np.asarray()没有修复它,它只是保持原样,我不断收到错误:

mask[y1:y2, x1:x2] = orig[y1:y2, x1:x2] TypeError: 'tuple' object does not support item assignment mask[y1:y2, x1:x2] = orig[y1:y2, x1:x2] TypeError: 'tuple' object 不支持项目分配

I can't find out why it does this and I also can't find a solution to fix it.我不知道它为什么会这样,我也找不到解决它的方法。

In your function definition, you have在您的 function 定义中,您有

def function(image, *mask):

specifically, you have defined *mask as argument.具体来说,您已将*mask定义为参数。 The * in front of the mask argument is actually special syntax for python, and means you could pass a variable number of arguments to your function. mask参数前面的*实际上是 python 的特殊语法,这意味着您可以将可变数量的 arguments 传递给 function。

The function wraps all theses arguments into a tuple named mask - which is why you have your error. function 将所有这些 arguments 包装到一个名为mask的元组中——这就是你有错误的原因。

For more info, read here .欲了解更多信息,请阅读此处

To fix, simply do要修复,只需执行

def function(image, mask):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM