Basic Python: Passing a string as an input to a function
<p>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.</p>

<pre><code>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
</code></pre>

<p>I want to pass the concatenated strings <code>n1</code> and <code>n2</code> as inputs to the equation <code>cv2.countNonZero((n1)/cv2.countNonZero(n2))</code>.</p>

<p>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. </p>

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

<p>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 <code>f_1</code>, <code>f_2</code>, etc, create a single list called <code>f</code> that contains each of the images.</p>

<p>For instance, instead of the code you have at the top, use:</p>

<pre><code>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]
]
</code></pre>

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

<p>Now, inside your loop, you can use:</p>

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

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

python string for-loop