Bharath S Bharath S - 3 months ago 11
Python Question

Basic Python: Passing a string as an input to a function

I am just starting off with python. I have 4 variables F_1, F_2, F_3 and F_4. Each containing a matrix in them. I want to count the non-zero values in each of them. So i wrote a loop.

f_1 = thresh1[1:mr, 1:mc]
f_2 = thresh1[1:mr, (mc+1):width]
f_3 = thresh1[(mr+1):height, 1:mc]
f_4 = thresh1[(mr+1):height, (mc+1):width]

b_1 = thresh2[1:mr, 1:mc]
b_2 = thresh2[1:mr, (mc+1):width]
b_3 = thresh2[(mr+1):height, 1:mc]
b_4 = thresh2[(mr+1):height, (mc+1):width]

for i in range(1, 5):
n1 = "f_"
n2 = "b_"
num = str(i)
n1 += num
n2 += num

r = cv2.countNonZero((n1)/cv2.countNonZero(n2))
print r

I want to pass the concatenated strings
as inputs to the equation

Here F1 is a binary image (F as in foreground) and B1 is also binary image (B as in Background). I am trying to compute the ratio of non zero pixels in foreground vs background.

r should be calculated for F1/B1 and in the next iteration F2/B2 ... so on


You have a problem in that you're trying to use strings to reference variable names. This is considerably difficult to do; you're better off using lists to contain your images. That is, instead of trying to reference f_1, f_2, etc, create a single list called f that contains each of the images.

For instance, instead of the code you have at the top, use:

f = [
  thresh1[1:mr, 1:mc],
  thresh1[1:mr, (mc+1):width],
  thresh1[(mr+1):height, 1:mc],
  thresh1[(mr+1):height, (mc+1):width]

b = [
  thresh2[1:mr, 1:mc],
  thresh2[1:mr, (mc+1):width],
  thresh2[(mr+1):height, 1:mc],
  thresh2[(mr+1):height, (mc+1):width]

Now you can reference what you were calling f_1 before with the code f[1].

Now, inside your loop, you can use:

for i in range(1, 5):
    r = cv2.countNonZero(f[i])/cv2.countNonZero(b[i])
    print r

I recommend you look into how to use lists in Python, as this is a fundamental datastructure. Also, there is a difference between "f_1" (which is a string) and f_1 (which is a variable named f_1). You can't (easily) go between the two.