我正在使用我在網上找到的這個函式,它的 add_speckle() 函式用于向影像添加散斑噪聲:
def add_speckle(k,theta,img):
gauss = np.random.gamma(k,theta,img.size)
gauss = gauss.reshape(img.shape[0],img.shape[1],img.shape[2]).astype('uint8')
noise = img img * gauss
也正在使用此方法將我的影像轉換為灰色影像,注意:此方法有助于將更改后的影像保持為陣列形式,而無需為它們提供 jpg 或 png 之類的格式,該方法:
def rgb2gray(rgb):
return np.dot(rgb[...,:3], [0.2989, 0.5870, 0.1140])
if __name__ == '__main__':
file_name = os.path.join('/content/img5.jpg')
img = rgb2gray(plt.imread(file_name))
問題是當我在我的噪聲影像上應用 rgb2gray 時,或者當我運行此命令時:
new_img = add_speckle(1,1,img)
發生錯誤,其訊息如下:
IndexError Traceback (most recent call last)
<ipython-input-89-d596c78bc99d> in <module>()
8
9 # img = cv2.imread('/content/img1.jpg')
---> 10 img1_g1 = add_speckle(1,1,img)
11 img1_g2 = add_speckle(8,8,img)
12 img1_g3 = add_speckle(22,22,img)
<ipython-input-83-df0363dc14bb> in add_speckle(k, theta, img)
2
3 gauss = np.random.gamma(k,theta,img.size)
----> 4 gauss = gauss.reshape(img.shape[0],img.shape[1],img.shape[2]).astype('uint8')
5 noise = img img * gauss
IndexError: tuple index out of range
該怎么辦,我真的需要幫助,因為我不想要任何其他的灰度轉換方法,因為通常它們包括需要保存或處理路徑和目錄的影像,而這種方法讓我只處理陣列形式的影像(無格式:jpg、png..等),并且讓您知道問題的根源是相同的 add_speckle() 函式,因為它生成影像,enter code here而不是灰度形式。
在此先感謝大家:)
uj5u.com熱心網友回復:
您正在從 RGB 轉換為灰度影像,但您的噪聲添加假定影像是 RGB。由于 NumPy 陣列的形狀是 2D,但您假設它是 3D,因此您會遇到越界錯誤。由于灰度轉換,情況并非如此。要與通道無關,請不要顯式訪問 shape 引數。實際上,您無需對陣列進行整形。它已經達到您期望的大小。請注意,您需要使用 shape 屬性,而不是 size:
def add_speckle(k,theta,img):
gauss = np.random.gamma(k,theta,img.shape)
noise = img img * gauss.astype(img.dtype)
return noise
這里額外的復雜性是將嘈雜的對應物轉換為與輸入影像相同的形式,以尊重在相同型別的兩個陣列之間執行的算術,但應注意不要使資料型別溢位。我沒有在這里明確檢查這個,我把它留給你來解決這個問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/475586.html
上一篇:使用ActivityResultContracts.GetContent()將影像保存到內部存盤。-(科特林/Java/Android)
