簡體   English   中英

如何均衡圖像並將其繪制為具有openCV和numpy的直方圖

[英]How do I equalize an image and plot it to an histogram with openCV and numpy

我試圖循環包含像素數據的nparray。 我想對每個像素值執行均衡,並將它們顯示為直方圖。

我已經通過以下方式實現了我的目標:

def stratch_contrast(img): 

    hist,bins = np.histogram(img.flatten(),256,[0,256])
    cdf = hist.cumsum()
    cdf_normalized = cdf * hist.max()/ cdf.max()

    cdf_m = np.ma.masked_equal(cdf,0)
    cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
    cdf = np.ma.filled(cdf_m,0).astype('uint8')
    img = cdf[img]

    plt.hist(img.flatten(),256,[0,256], color = 'black')
    plt.xlim([0,256])
    plt.legend(('cdf','histogram'), loc = 'upper left')
    plt.show()

    img = cv2.imread(name,0)
    equ = cv2.equalizeHist(img)
    res = np.hstack((img,equ)) #stacking images side-by-side
    cv2.imwrite('res.png',res)

    return

但我真的很想這樣做而沒有使用預定義的函數進行學習。

所以我試着跟隨:

 def stratch_contrast(img, darkestValue, whitestValue):

     newImgPixelList = []

     h = img.shape[0] #number of pixels in the hight
     w = img.shape[1] #number of piexels in the weight

     darkestValueStratch = 256 #opposite so it can get darker while loop
     whitestValueStratch = 0 #opposite so it can get lighter while loop

     for y in range(0, w):
         for x in range(0, h):
              newImg[x][y] = (img[x][y]-darkestValue)*256/(whitestValue-darkestValue)
              pxStratch = newImg[x][y]
              newImgPixelList.append(pxStratch)
              if darkestValueStratch > pxStratch:
                  darkestValueStratch = pxStratch
              if whitestValueStratch < pxStratch:
                  whitestValueStratch = pxStratch   

      return newImgPixelList, darkestValueStratch, whitestValueStratch

但是當我調用我的繪圖函數時,就像這樣:

plot(newImgPixelList, int(darkestValueStratch), int(whitestValueStratch))

繪制的直方圖根本不均衡。 它看起來幾乎完全一樣,就像我沒有均衡的直方圖一樣,所以一定是錯的。 如果有人可以幫助我,我將非常感激!

我的完整代碼:

import matplotlib.pyplot as plt
import numpy as np
import cv2
np.seterr(over='ignore')

name = 'puppy.jpg'

img = cv2.imread(name, cv2.IMREAD_GRAYSCALE) #import image
newImg = np.zeros((img.shape))

def get_histo_scope(img):

    imgPixelList = [] #array which later can save the pixel values of the image

    h = img.shape[0] #number of pixels in the hight
    w = img.shape[1] #number of piexels in the weight

    darkestValue = 256 #opposite so it can get darker while loop
    whitestValue = 0 #opposite so it can get lighter while loop

    for y in range(0, w):
        for x in range(0, h):       
            px = img[x][y] #reads the pixel which is a npndarray [][][]
            imgPixelList.append(px) #saves the pixel data of every pixel we loop so we can use it later to plot the histogram
            if darkestValue > px: #identifies the darkest pixel value
                darkestValue = px
            if whitestValue < px: #identifies the whitest pixel value
                whitestValue = px 

    return darkestValue, whitestValue, imgPixelList

def plot(imgPixelList, darkestValue, whitestValue):
    values = range(darkestValue, whitestValue, 1) #creates and array with all data from whitesValue to darkestValue
    bin_edges = values

    plt.hist(imgPixelList, bins=bin_edges, color='black')
    plt.xlabel('Color Values')
    plt.ylabel('Number of Poxels')
    plt.show()  

    return     

def stratch_contrast(img, darkestValue, whitestValue): 

    #hist,bins = np.histogram(img.flatten(),256,[0,256])
    #cdf = hist.cumsum()
    #cdf_normalized = cdf * hist.max()/ cdf.max()

    #Comment out to remove Equalization 
    #cdf_m = np.ma.masked_equal(cdf,0)
    #cdf_m = (cdf_m - cdf_m.min())*255/(cdf_m.max()-cdf_m.min())
    #cdf = np.ma.filled(cdf_m,0).astype('uint8')
    #img = cdf[img]

    #plt.hist(img.flatten(),256,[0,256], color = 'black')
    #plt.xlim([0,256])
    #plt.legend(('cdf','histogram'), loc = 'upper left')
    #plt.show()

    #img = cv2.imread(name,0)
    #equ = cv2.equalizeHist(img)
    #res = np.hstack((img,equ)) #stacking images side-by-side
    #cv2.imwrite('res.png',res)

    newImgPixelList = []

    h = img.shape[0] #number of pixels in the hight
    w = img.shape[1] #number of piexels in the weight

    darkestValueStratch = 256 #oposite so it can get darker while loop
    whitestValueStratch = 0 #oposite so it can get lighter while loop

    for y in range(0, w):
       for x in range(0, h):
            newImg[x][y] = (img[x][y]-darkestValue)*256/(whitestValue-darkestValue)
            pxStratch = newImg[x][y]
            newImgPixelList.append(pxStratch)
            if darkestValueStratch > pxStratch: #identifies the darkest pixel value
                darkestValueStratch = pxStratch
            if whitestValueStratch < pxStratch: #identifies the whitest pixel value
                whitestValueStratch = pxStratch   

    return newImgPixelList, darkestValueStratch, whitestValueStratch

darkestValue, whitestValue, imgPixelList = get_histo_scope(img) #get scope and pixel values from the img data

plot(imgPixelList, darkestValue, whitestValue) #plot the collected pixel values

newImgPixelList, darkestValueStratch, whitestValueStratch = stratch_contrast(img, darkestValue, whitestValue)

plot(newImgPixelList, int(darkestValueStratch), int(whitestValueStratch))

我認為你誤解了對比度拉伸算法。

該算法的目標是線性縮放像素的值,以便您的圖像使用可用的完整動態范圍,即min(I) = 0max(I) = 255

為此,您必須循環像素並縮放它們之前找到當前的min(I)max(I) 只需遍歷整個圖像,同時跟蹤每個通道的最大值和最小值(RGB圖像的3個通道)。 然后使用這些值使用公式newValue = 255 * (oldValue - minimum) / (maximum - minimum)來縮放像素。 獨立處理每個R,G和B通道

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM