0

img 值的屏幕截图2 [这是原始的] 3 [这是预期的输出]这是我得到的输出我正在尝试在 python 中将灰度级从 to 拉伸,0-10050-200输出图像不正确。我画了一条直线,表示两个范围之间的线性关系,在第 8 行中,我使用这个等式来获得输出。我的代码有什么问题?

这是我的第一个问题,如有错误,请见谅。

def Contrast_enhancement(img):
    newimg = img
    height = img.shape[0]
    width = img.shape[1]
    for i in range(height):
       for j in range(width):
           if(img[i][j] * 255 >= 0 and img[i][j] * 255 <= 100):
               newimg[i][j] = (((3/2) * (img[i][j] * 255)) + 50)/255
    return newimg
4

2 回答 2

0

你的问题有两个答案:

  • 一个是严格的技术性(@DonQuiKong 试图回答的那个),指的是如何更简单或更正确地进行拉伸。
  • 另一个是隐含的,试图回答你实际的图像拉伸问题。

我在这里关注第二种情况。从您提供的图像样本来看,您没有采取正确的方法。让我们考虑一下您提供的样本确实具有介于 0-100 之间的所有强度值(从我的电脑中的屏幕捕获来看,它们没有,但这在一定程度上取决于屏幕)。您的方法似乎是正确的,应该可以处理小错误。

1)例如,一个小错误是:

newimg = img

不做你认为它做的事。它确实创建了原始变量的别名。利用:

newimg = img.copy()

反而。

2)如果您收到具有不同边界的图像,则您的代码已损坏。由于某种原因,它会忽略一些像素,我猜这不是你想要的。

3)在这种情况下,您可以使用以下方法将您想要的拉伸应用于整个图像:

newimg -= np.min(newimg)
newimg /= np.max(newimg)

这只是将您的强度延伸到 0-255 边界。

4)从您的示例图像来看,您还需要更彻底的拉伸(这将牺牲一些图像信息以增加图像对比度)。您可以使用下限代替上述内容:

    newimg -= np.min(newimg)
    newimg /= (np.max(newimg) * 0.5)

这有效地“燃烧”了一些像素,但在你的情况下,结果看起来更接近你想要的。除此之外,您可以将旧强度的非线性映射(例如对数映射)应用于新强度,并且不会得到任何“烧毁”像素。

值为 0.5 的样本:
在此处输入图像描述

于 2018-11-02T13:54:49.303 回答
0
import numpy as np
import copy
def Contrast_enhancement(img):
    newimg = np.array(copy.deepcopy(img)) #this makes a real copy of img, if you dont, any change to img will change newimg too
    temp_img=np.array(copy.deepcopy(img))*3/2+50/255
    newimg = np.where(newimg<=100,temp_img,newimg)
    return newimg

或更短:

import numpy as np
import copy
def Contrast_enhancement(img):
    newimg = np.array(copy.deepcopy(img)) #this makes a real copy of img, if you dont, any change to img will change newimg too

    newimg = np.where(newimg<=100,newimg*3/2+50/255,newimg)
    return newimg

复制部分应该解决您的问题,而 numpy 部分只是为了加快速度。如果 newimg <=100,Np.where 返回 temp_img,否则返回 newimg。

于 2018-11-02T13:31:29.983 回答