Isaac
Isaac

Reputation: 344

Python Boolean in Brackets?

I'm working on OpenCV using python, and in the edge detection script here I've encountered something I've never seen before. I apologize if this question has been asked before on here, but I'm not really sure what to search for.

I've pasted the relevant piece below:

while True:
    flag, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    thrs1 = cv2.getTrackbarPos('thrs1', 'edge')
    thrs2 = cv2.getTrackbarPos('thrs2', 'edge')
    edge = cv2.Canny(gray, thrs1, thrs2, apertureSize=5)
    vis = img.copy()
    vis /= 2
    vis[edge != 0] = (0, 255, 0) #This is the line I'm trying to figure out
    cv2.imshow('edge', vis)

The code isn't mine, but is part of the OpenCV documentation. As best as I can tell, vis[edge != 0] is going through each element in edge, comparing it to true, and then somehow (this is the strange part to me) turning the result of the boolean evaluation into xy coordinates for vis, and then setting the image value to green.

It just seems a little magical to me, as I've never encountered anything like this, since I'm mostly a C/C++ programmer. Can someone point me to the docs where I can read up on it? I have STFW unsuccessfully because I don't know what to call this behavior.

Upvotes: 1

Views: 301

Answers (1)

chris
chris

Reputation: 4996

vis is a numpy array, and the [edge != 0] seems like syntactic sugar for the numpy.where() function...so its thresholding the values with Canny and then drawing a green line on the vis image where the edges are.

Here is an analogous example.

import numpy as np
x = np.arange(10)
y = np.zeros(10)
print y
y[x>3] = 10
print y

Upvotes: 2

Related Questions