我正在嘗試創建一個程式,在該程式中我應該能夠使用 python 和 opencv 將一個影像覆寫在另一個基本影像上,并將輸出影像存盤在另一個檔案夾中。我正在使用 opencv 來實作這一點,但是我撰寫的代碼沒有給出想要的結果。
import cv2
from os import listdir
from os.path import isfile, join
import numpy as np
path_wf = 'wf_flare'
path_fr = 'captured_flare'
files_wf = [ f for f in listdir(path_wf) if isfile(join(path_wf,f))]
files_fr = [ fl for fl in listdir(path_fr) if isfile(join(path_fr,fl))]
img_wf = np.empty(len(files_wf), dtype = object)
img_fr = np.empty(len(files_fr), dtype = object)
img = np.empty(len(files_wf), dtype = object)
k = 0
for n in range(0, len(files_wf)):
img_wf[n] = cv2.imread(join(path_wf, files_wf[n]))
img_fr[k] = cv2.imread(join(path_fr, files_fr[k]))
print("Done Reading" str(n))
img_wf[n] = cv2.resize(img_wf[n], (1024,1024),interpolation = cv2.INTER_AREA)
img[n] = 0.4*img_fr[k] img_wf[n]
fn = listdir(path_wf)
name = 'C:\Flare\flare_img' str(fn[n])
print('Creating...' name str(n 10991))
cv2.imwrite(name,img[n])
k = 1
if(k%255 == 0):
k = 0
else:
continue
檔案夾組織粘貼如下:



我希望輸出影像來到這里:

uj5u.com熱心網友回復:
以下行中有兩個問題:
name = 'C:\Flare\flare_img' str(fn[n])
- 在 Python 中,字串中的特殊字符使用反斜杠進行轉義。一些示例是
\n(換行符)、\t(制表符)、(換頁)\f等。在您的情況下,\f是導致路徑格式錯誤的特殊字符。解決此問題的一種方法是通過r在第一個引號前添加一個來使用原始字串:
'C:\Flare\flare_img'
Out[12]: 'C:\\Flare\x0clare_img'
r'C:\Flare\flare_img'
Out[13]: 'C:\\Flare\\flare_img'
- 創建檔案系統路徑時不要只連接字串。遲早你最終會放錯路徑分隔符。在這種情況下,它是缺失的,因為
fn[n]它不是從一開始的。這么說吧fn[n] = "spam.png"。然后假設你這樣做
name = r'C:\Flare\flare_img' str(fn[n])
你的價值name將是
C:\\Flare\\flare_imgspam.png
這不是你想要的。
使用os.path.join或pathlib.Path之前建議的現代。包裝fn[n]在str函式中也是多余的,因為os.listdir已經回傳了一個字串串列。
您需要進行的更改如下:
# add to imports section
from pathlib import Path
# add before for-loop
out_path = Path(r'C:\Flare\flare_img')
# change inside for-loop
name = out_path / fn[n]
檔案:Python字串
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/365637.html
