简体   繁体   中英

filtering 2D images in numpy array and calculate in python

I imported an image with three bands. And I entered each band into a numpy array.

Now I try to modify the value of band 1, conditional on band 3.

However, my image has many zero values and must be computed with the exception of zero to speed up the operation.

I think it is faster to find values after excluding the 0 value.

Below is the code I used to do.

cols = 0 
rows = 0
[cols,rows] = test.shape
i= 0
i2 = 0

while i < cols:
    k = 0
    k2 =0
    while k <rows:
        if 0.15>test[i,k]>0.05089 and  30> test3[i,k]>29.8  :
            test[i,k] = 1
....

Well it looks like what you want is to select a "mask" and assign to it. Your example is a bit strange and incomplete, but you could achieve what I think you're intending to achieve by replacing the loop with:

test[(0.15>test) & (test>0.05089) & (30>test3) & (test3>29.8)] = 1

What's going on here:

  • (0.15>test) create a boolean array the same size as test with all elements < 0.15 set to True and the rest False .
  • The & operators do an elementwise logical AND with the other boolean arrays to make a new boolean array (also the same size as test and test3)
  • test[XXX] = 1 means "take all elements of XXX which are true, and set the corresponding elements of test to 1" (it's assumed that XXX has the same shape as test (or can be broadcasted to the same shape))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM