比较两个二进制图像并可视化差异

时间:2018-03-12 15:55:01

标签: python arrays numpy image-processing

我想比较2个二进制图像,并希望在两个图像ref.pngextracted.png中直观地显示真正的正面,误报和误判,如下例所示。

参考: reference提取 extracted

质量: quality

(白色= TP,红色=假阳性,绿色=假阴性)

我使用以下算法,但有更高效的方法吗?

def numpytoimage(numpy):
    numpy = numpy * 255
    image= Image.fromarray(numpy.astype(np.uint8))
    return image


reference = cv2.imread("ref.png",0)
_, thresh_ref = cv2.threshold(reference, 75, 255, 0)

extract = cv2.imread("extract.png",0)
_, thresh_extract = cv2.threshold(extract, 75, 255, 0)


C = np.zeros(shape=(len(thresh_ref), len(thresh_ref[0]), 3))

for i in range (0, thresh_ref.shape[0],1):
    for j in range(0, thresh_ref.shape[1], 1):
        if thresh_ref[i][j] == thresh_extract[i][j] and thresh_ref[i][j] == 0:
            C[i][j] = 1
        elif thresh_ref[i][j] == 0:
            C[i][j][0] = 0
            C[i][j][1] = 1
            C[i][j][2] = 0
        elif thresh_extract[i][j] == 0:
            C[i][j][0] = 1
            C[i][j][1] = 0
            C[i][j][2] = 0
        else:
            C[i][j][0] = 0.5
            C[i][j][1] = 0.5
            C[i][j][2] = 0.5

C_image = numpytoimage(C)
C_image.save("quality.png")

2 个答案:

答案 0 :(得分:1)

如果将图像阈值设置为[0,1]和[0,2]并将它们加在一起,则会获得不同条件的所有唯一值。由于值为0到3,您可以直接使用它们索引到查找表中:

lut = [[  1,  1,  1],
       [  1,  0,  0],
       [  0,  1,  0],
       [0.5,0.5,0.5]]

_, thresh_ref = cv2.threshold(reference, 75, 1, 0)
_, thresh_extract = cv2.threshold(extract, 75, 2, 0)
C = lut[thresh_ref + thresh_extract]

答案 1 :(得分:0)

  1. 使用C[i,j,ch]代替C[i][j][ch]。第二种方法创建一个临时数组,这会降低性能。

  2. 使用item()的python原生数值,比numpy标量更快:thresh_ref.item(i, j), thresh_extract.item(i, j)