更改图像矩阵的{d}后图像显示错误

时间:2016-10-15 21:52:55

标签: python opencv numpy

我正在使用opencv + python来处理眼底(视网膜图像)。将float64图像转换为uint8图像时存在一个问题。

以下是python代码:

import cv2
import matplotlib.pyplot as plt
import numpy as np
from tkFileDialog import askopenfilename

filename = askopenfilename()
a = cv2.imread(filename)
height, width, channel = a.shape
b, Ago, Aro = cv2.split(a)
mr = np.average(Aro)
sr = np.std(Aro)

Ar = Aro - np.mean(Aro)
Ar = Ar - mr - sr

Ag = Ago - np.mean(Ago)
Ag = Ag - mr - sr

#Values of elements in Ar
#    Ar = [[-179.17305527, -169.17305527, -176.17305527, ..., -177.17305527, -177.17305527, -177.17305527],
#           [-178.17305527, -169.17305527, -172.17305527, ..., -177.17305527, -177.17305527, -177.17305527],
#           [-179.17305527, -178.17305527, -179.17305527, ..., -177.17305527, -177.17305527, -177.17305527],
#           ...,
#           [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527],
#           [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527],
#           [-177.17305527, -177.17305527, -177.17305527, ..., -177.17305527, -177.17305527, -177.17305527]]

Mr = np.mean(Ar)
SDr = np.std(Ar)

print "MR = ", Mr, "SDr = ", SDr

Mg = np.mean(Ag)
SDg = np.std(Ag)
Thg = np.mean(Ag) + 2 * np.std(Ag) + 50 + 12

Thr = 50 - 12 - np.std(Ar)
print "Thr = ", Thr
Dd = np.zeros((height, width))
Dc = Dd
for i in range(height):
    for j in range(width):

        if Ar[i][j] > Thr:
            Dd[i][j] = 255
        else:
            Dd[i][j] = 0

TDd = np.uint8(Dd)
TDd2 = Dd

for i in range(height):
    for j in range(width):
        if Ag[i][j] > Thg:
            Dc[i][j] = 1
        else:
            Dc[i][j] = 0

#CALCULATING RATIO
ratio = 500.0 / Dd.shape[1]
dim = (500, int(Dd.shape[0] * ratio))
#
# #RESIZING TO-BE-DISPLAYED IMAGES
resized_TDd = cv2.resize(TDd, dim, interpolation=cv2.INTER_AREA)
resized_TDd2 = cv2.resize(TDd2, dim, interpolation=cv2.INTER_AREA)
resized_original = cv2.resize(Aro, dim, interpolation=cv2.INTER_AREA)

cv2.imshow('TDd', resized_TDd)
cv2.imshow('TDd2', resized_TDd2)
cv2.imshow('Aro', resized_original)
cv2.waitKey(0)

Ar[][]具有-ve和+ ve值,Thr具有-ve值。 Dd是我想要显示的图片。问题是TDd显示一个奇怪的图像(255s和0s被分配给适当的像素,我检查过但显示的图片很奇怪,与TDd

不相似

原始图片

enter image description here

红色频道图片

enter image description here

TDd(Dd的uint8):

enter image description here

TDd2(与Dd相同)

enter image description here

Dd2(初始化时声明uint8 dtype)

enter image description here

为什么TDdTDd2图片有所不同? 由于这2幅图像中像素的灰度值(据我所知和已知)之间的差异仅为255,0 (在TDd中)和255.0,0.0 (在TDd2)

如果有人能告诉我,这将是一个很大的帮助。

2 个答案:

答案 0 :(得分:1)

通常当图像用np float64数组表示时,RGB值的范围为0到1.因此,当转换为uint8时,从float64转换为uint8时可能会出现精度损失。

我会直接创建Dd作为:

Dd = np.zeros((height, width), dtype=np.uint8)

然后它应该工作。

答案 1 :(得分:1)

看看我执行了你的代码,还有results

他们看起来很正常......这就是我用过的code

Ar与其他人不同,因为当你imShow()时,它会将值设为白色的地方为>否则为0黑色。游览代码后的其他矩阵变为白色,其中> Thr小于0,因此更多像素显然变白。

<强>更新

当您应该完成Dc = np.zeros((身高,宽度))时,您已将Dd分配给Dc。