所以我試圖在矩陣的某一行和一個像素之間取得區別,但我得到了一個錯誤。
其中 colorPal 是一個 8x3 矩陣:
colorPal = np.matrix('0., 0., 0.;'
'0., 0., 1.;'
'0., 1., 0.;'
'0., 1., 1.;'
'1., 0., 0.;'
'1., 0., 1.;'
'1., 1., 0.;'
'1., 1., 1.;')
,并且我試圖從該矩陣的某些行中減去 RGB 通道中的三個值:
colorPal[0] - pix
其中 pix 是:
a certain pixel with 3 channels (RGB) from image,
and I'm accesing it by specifying row and column of that image (img):
So, pix = img[i,j]
對于 colorPal 的第一行,某些像素值是:
colorPal[0] = [[0. 0. 0.]]
pix = [0.81 0.81 0.81]
在上面 ( colorPal[0] - pix) 的操作之后,我得到了一個結果:
[[-0.81 -0.81 -0.81]]
所以它被減去了。現在我想把整行的第二次冪((colorPal[0] - pix)**2)。但是 numpy 拋出這個:
raise LinAlgError('Last 2 dimensions of the array must be square')
numpy.linalg.LinAlgError: Last 2 dimensions of the array must be square
我怎樣才能將整排提升到二次方?這段代碼有什么問題?
uj5u.com熱心網友回復:
問題是您將其定義為 2D 矩陣,并且從中獲取的切片colorPal[0]仍將是 2D 矩陣(即使維度的 1 現在具有 size 1)。
如果您嘗試將該 2D 矩陣與其自身相乘,則它需要最后兩個維度具有相同的大小,而他們沒有,1 != 3。
你可以這樣做:
import numpy as np
colorPal = np.matrix('0., 0., 0.;'
'0., 0., 1.;'
'0., 1., 0.;'
'0., 1., 1.;'
'1., 0., 0.;'
'1., 0., 1.;'
'1., 1., 0.;'
'1., 1., 1.')
pix = np.array([0.81, 0.81, 0.81])
print((np.asarray(colorPal[0]).squeeze() - pix) ** 2)
這將切片并將其轉換為具有相同大小和維度的陣列,然后將其壓縮以將其轉換為一維陣列,該陣列可以根據需要與自身相乘。
結果:
[0.6561 0.6561 0.6561]
或者你可以避免復雜性,colorPal首先將所有的都變成一個陣列,這樣你就不必對每種顏色都執行轉換:
import numpy as np
colorPal = np.matrix('0., 0., 0.;'
'0., 0., 1.;'
'0., 1., 0.;'
'0., 1., 1.;'
'1., 0., 0.;'
'1., 0., 1.;'
'1., 1., 0.;'
'1., 1., 1.')
pix = np.array([0.81, 0.81, 0.81])
colorPal = np.asarray(colorPal)
print((colorPal[0] - pix) ** 2)
結果相同。
從您對此答案的評論來看,您似乎想要實際修改或替換colorPal應用于每種顏色的操作。將矩陣轉換為陣列后,這很容易:
import numpy as np
colorPal = np.matrix('0., 0., 0.;'
'0., 0., 1.;'
'0., 1., 0.;'
'0., 1., 1.;'
'1., 0., 0.;'
'1., 0., 1.;'
'1., 1., 0.;'
'1., 1., 1.')
pix = np.array([0.81, 0.81, 0.81])
result = (np.asarray(colorPal) - pix) ** 2
print(result)
結果:
[[0.6561 0.6561 0.6561]
[0.6561 0.6561 0.0361]
[0.6561 0.0361 0.6561]
[0.6561 0.0361 0.0361]
[0.0361 0.6561 0.6561]
[0.0361 0.6561 0.0361]
[0.0361 0.0361 0.6561]
[0.0361 0.0361 0.0361]]
或者您可以在型別轉換后就地完成所有操作:
colorPal = np.asarray(colorPal)
colorPal -= pix
colorPal *= colorPal
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456518.html
標籤:Python python-3.x 麻木的 图像处理
上一篇:Elastic8.1.1-無法實體化FunctionScore,build()受保護
下一篇:將histeq函式應用于3x3塊
