我正在嘗試將 Andrew Ng 課程中的基本神經網路應用程式從 Python 移植到 Julia,但在這一部分中被卡住了。
我正在使用自己的資料集,因此我正在創建自己的解決方案來處理影像并調整它們的大小。為了與 Python 代碼中的完全相同(并將所有影像作為向量放在一個矩陣中),我需要將它們從 RGB 轉換為 Array 型別,以便我可以將它們作為列存盤在矩陣中,但我一直出錯而且我似乎無法在其他任何地方找到資訊。
我目前正在使用此處提出的想法的改編版本。
using Images, FileIO, TestImages
cat_path = "path/Cat/"
cat_imgs = joinpath.(cat_path, readdir(cat_path))
function process_image(path_vec::Vector{String}, h::Int64, w::Int64, label::Int64)
result = zeros((h*w), length(path_vec))
class = []
for i in enumerate(path_vec)
img = load(i[2])::Array{RGB{N0f8},2}
img = imresize(img,(h,w))::Array{RGB{N0f8},2}
img = vec(img)::Vector{RGB{N0f8}}
result[:,i[1]] = img # this is the line where I believe Im getting the error
push!(class, label)
end
return result, class
end
如果我嘗試將影像從 RGB 更改為灰色,它可以作業(這是有道理的,因為它們只有一個通道并且很容易變成一個陣列),但是如果我想將所有通道保留在向量中,我不能只使用 save將它們作為 Vector{RGB{N0f8}} 放入矩陣中,如果我嘗試使用img = convert(Array{Float64,1},img)我會得到錯誤:MethodError: Cannot 轉換 an object of type RGB{N0f8} to an object of type Float64
我不確定如何使代碼易于重現,但我相信如果您創建一個包含單個影像的檔案夾并更新檔案路徑,它應該是可能的。或者只是使用測驗影像運行函式內的各個行:
using TestImages
img = testimage("mandrill")
uj5u.com熱心網友回復:
只需使用channelview. 請注意,RGB 值將作為第一個維度提供。
julia> channelview(testimage("mandrill"))
3×512×512 reinterpret(reshape, N0f8, ::Array{RGB{N0f8},2}) with eltype N0f8:
[:, :, 1] =
0.643 0.471 0.388 … 0.475 0.494 0.035
0.588 0.49 0.29 0.58 0.663 0.043
0.278 0.243 0.122 0.608 0.659 0.047
;;; …
[:, :, 512] =
0.702 0.471 0.376 … 0.318 0.314 0.016
0.737 0.541 0.314 0.314 0.247 0.02
0.463 0.29 0.192 0.235 0.278 0.008
如果您想擁有不同的尺寸布局,您可以permutedims使用channelview:
julia> permutedims(channelview(testimage("mandrill")),[2,3,1])
512×512×3 Array{N0f8,3} with eltype N0f8:
[:, :, 1] =
0.643 0.247 0.294 0.373 0.616 … 0.275 0.569 0.459 0.553 0.702
0.471 0.529 0.216 0.294 0.455 0.51 0.478 0.478 0.533 0.471
? ? ?
uj5u.com熱心網友回復:
在丹的建議之后,我設法找到了一個解決方案,雖然可能是一個緩慢/低效的解決方案:
function process_image(path_vec::Vector{String}, h::Int64, w::Int64, label::Int64)
result = zeros((h*w*3), length(path_vec))
class = []
for i in enumerate(path_vec)
img = load(i[2])::Array{RGB{N0f8},2}
img = imresize(img,(h,w))::Array{RGB{N0f8},2}
img = vec(img)::Vector{RGB{N0f8}}
img = [temp(img[i]) for i = 1:length(img), temp in [red, green, blue]]
img = reshape(img, ((h*w*3),1))
result[:,i[1]] = img
push!(class, label)
end
return result, class
end
如果代碼中不清楚,我所做的是將每個顏色通道的 3 個陣列提取到一個矩陣中,從而生成一個 1024x3 陣列{N0f8,2}。然后你可以將這個陣列重塑為一個 3072x1 陣列{N0f8,2}。重新整形后,您可以將其添加到零矩陣并轉換為 Array{Float64,2}。
我不得不手動輸入通道數以獲得正確的尺寸,這不是很高興,但它確實有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/527446.html
