2

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

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.

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:

(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:

mask[y1:y2, x1:x2] = orig[y1:y2, x1:x2] TypeError: 'tuple' object does not support item assignment

I can't find out why it does this and I also can't find a solution to fix it.

NielsNL4
  • 580
  • 1
  • 8
  • 21
  • 1
    I can't reproduce your error - mind to try to come up with a [mcve] (i.e. simulated `image` and fake `masked` arrays, and a sample `results` list?) – rafaelc Oct 07 '19 at 14:11

1 Answers1

1

In your function definition, you have

def function(image, *mask):

specifically, you have defined *mask as argument. 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.

The function wraps all theses arguments into a tuple named mask - which is why you have your error.

For more info, read here.

To fix, simply do

def function(image, mask):
rafaelc
  • 57,686
  • 15
  • 58
  • 82