I'm working with image manipulation in Python.
I came across a line of code like:
image[dst > 0.01 * dst.max()] = [0, 0, 255]
Being "image" and "dst" images.
Is what's inside the "" brackets, indexing "image" a condition for the pixel of that image? Will the assignment take effect when the condition is true?
It's a little difficult to answer your question without context. However, I assume these images are stored as vectors and numeric matrices.
If my guess is correct, this is called "logical indexing", similar to what numpy provides (if it's not quite the same thing).
I'll explain it through an example using numpy. We start by creating a vector:
>>> import numpy as np >>> l = [1,2,3,4] >>> l [1, 2, 3, 4] >>> x = np.array(l) >>> x array([1, 2, 3, 4])
The vector and the list behave quite differently. Noteworthy is the following:
>>> l>2 True >>> x>2 array([False, False, True, True], dtype=bool)
When you do a comparison between a vector and a number, the result is a logical vector with the comparison value for each element of the vector. This is true for more complex comparisons as well:
>>> l%2==0 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for %: 'list' and 'int' >>> x%2==0 array([False, True, False, True], dtype=bool)
And when you use a logical vector in place of the index of another vector, the result is a vector with all the elements corresponding to positions occupied by "True" in the logical vector:
>>> x[x>2] array([3, 4]) >>> x[x%2==0] array([2, 4])
Finally, when you make an assignment, this one applies to the elements of the original vector:
>>> x[x%2==0] *= 10 >>> x array([ 1, 20, 3, 40])
You can assign a list, and the list values are passed in order:
>>> x[x%2==1] = [-1,-3] >>> x array([-1, 20, -3, 40])
But the list needs to be the right length. That is, if you have
n values that satisfy the condition and you pass a list, the list must have exactly
>>> x[x%2==1] = [-1,-3, -5] >>> x[x%2==0] = range(10, 150, 10) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: NumPy boolean array indexing assignment cannot assign 3 input values to the 2 output values where the mask is true >>> x = np.array(range(15)) >>> x[x%2==0] = [-1,-3] Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: NumPy boolean array indexing assignment cannot assign 2 input values to the 8 output values where the mask is true
What your code snippet does is equivalent to that. Putting it in words: the positions of the vector
image corresponding to the positions of the vector
dst where the value is greater than 1% of the maximum of this vector receive the values [0,0,255].
Since this looks like a trio of RGB values, I guess what's happening isn't exactly the same as assigning a list to a vector. Most likely
dst pixels satisfying the condition will match blue pixels in