我有两张尺寸相同的图片。
图像是numpy数组,我正在检查像素并获取每个像素的if [ -n "${WSREP_SST_OPT_ADDR_PORT:-}" ]; then
if [ -n "${WSREP_SST_OPT_PORT:-}" ]; then
...
else
readonly WSREP_SST_OPT_PORT="$WSREP_SST_OPT_ADDR_PORT"
fi
fi
# Start of the workaround
if [ -z "${WSREP_SST_OPT_PORT:-}" ]; then
readonly WSREP_SST_OPT_PORT="4444"
fi
# End of the workaround
r
g
,如下所示:
b
然后我在两个像素之间获取MSE,如:
for i in range(len(img1)):
for j in range(len(img1[0])):
pimg1 = img1[i][j]
pimg2 = img2[i][j]
r1 = pimg1[0]
r2 = pimg2[0]
g1 = pimg1[1]
g2 = pimg2[1]
b1 = pimg1[2]
b2 = pimg2[2]
问题是这是非常缓慢的。有没有更有效的方法来做到这一点?
我希望制作具有特定"阈值"的所有像素。相似性,两个图像之间,黑色。并且所有与mse = math.sqrt(((r1 - r2) ** 2) + ((g1 - g2) ** 2) + ((b1 - b2) ** 2))
的像素差异较大的像素。
img2
我正在捕捉像这样的图像:
if mse > threshold:
new_img[i][j] = pimg2
else:
new_img[i][j] = [0, 0, 0] # black pixel
我得到的图片如下:
for frame in cam.camera.capture_continuous(raw, format="rgb", use_video_port=True):
img = frame.array
cv2.imwrite("image.png", img)
答案 0 :(得分:3)
只需在差异上使用np.linalg.norm
-
mse = np.linalg.norm(img1-img2,axis=2)
使用np.einsum
-
d = (img1-img2).astype(float)
mse = np.sqrt(np.einsum('...i,...i->...',d,d))
运行时测试 -
In [46]: np.random.seed(0)
...: m,n = 1024,1024
...: img1 = np.random.randint(0,255,(m,n,3)).astype(np.uint8)
...: img2 = np.random.randint(0,255,(m,n,3)).astype(np.uint8)
In [47]: %timeit np.linalg.norm(img1-img2,axis=2)
10 loops, best of 3: 26.6 ms per loop
In [49]: %%timeit
...: d = (img1-img2).astype(float)
...: mse = np.sqrt(np.einsum('...i,...i->...',d,d))
100 loops, best of 3: 13 ms per loop
要为black
值小于某个阈值MSE
的像素创建一个设置为mse_thresh
的输出数组,并从img2
中选择,否则,这里是附加代码 -
mask = mse >= mse_thresh
out = np.where(mask[...,None], img2, 0)
将所有内容拼接在一起 - 使用einsum
计算平方MSE
值,并与主要改进的平方MSE阈值进行比较,并将输出分配回img2
-
d = (img1-img2).astype(float)
mse = np.einsum('...i,...i->...',d,d)
img2[mse < mse_thresh**2] = 0