Numpy 二维图像数组如何仅将公式应用于满足条件的像素?

Numy 2D image array how to apply formula to only pixels that satisfy a condition?

import numpy as np
from PIL import Image

def isblack(rgb):
    return (rgb[0]==0) and (rgb[1]==0) and (rgb[2]==0)

a = Image.open('image1.jpg')
a = np.array(a) # RGB image
[h,w,chan] = np.shape(a)
filtsz = 9
# comparing subimage with a[50:59,60:69] and a[100:119,120:129], for example
srcTop = 50
srcLeft = 60
dstTop = 100
dstLeft = 120 

ssd = 0 # sumOfSquareDifference
for i in range(filtsz):
  for j in range(filtsz):
    if not isblack(a[dstTop+i,dstLeft+j,:]):
      ssd += sum((a[dstTop+i, dstLeft+j] - a[srcTop+i, srcLeft+j])**2)
print(ssd)

    

朴素的实现是遍历所有满足条件的像素,然后计算。 但是,这很慢。

我怎样才能让它更快?我正在寻找一种使用索引的方法。例如,具有以下伪代码的东西:

selected = [not isblack(pixel) for pixel in image] # 2D array contains 0 if black, 1 if not black
diff = [(a[pixel] - b[pixel])**2 for pixel in a] # 2D array contains the square difference at each pixel
ssd = sum(diff * selected) # sum only positions that satisfy the condition
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
img = Image.open("image/image1.jpg")
filtsz = 100 # increase from 9 to 100 for display purpose
srcTop = 50
srcLeft = 60
dstTop = 100
dstLeft = 120
npimg = np.array(img)
# indexing
subimg_src = npimg[srcTop:srcTop+filtsz,srcLeft:srcLeft+filtsz,:] 
subimg_dst = npimg[dstTop:dstTop+filtsz,dstLeft:dstLeft+filtsz,:]
fig,ax = plt.subplots(1,2)
ax[0].imshow(subimg_src)
ax[1].imshow(subimg_dst)

# channel axis - 2
# ~: negation operator
# keepdims: set True for broadcasting
selected = ~np.any(subimg_dst,axis=2,keepdims=True) 
ssd = np.sum((subimg_src-subimg_dst)**2*selected)
print(ssd) 

示例图片: