我已經按順序生成圖像并保存在名為detected_car文件夾的目錄中,然后我想將它們發送到 JSON API 之類https://api.generate_json/的,當我從 API 獲得 json 響應時,它也會自動刪除os.remove("%s" %file),但它總是會出現該錯誤。這是我的代碼:import cv2import osimport jsonimport requestsimport timecar_count = [0]current_path = os.getcwd()file = 'detected_car/car' + str(len(car_count)) + ".png"path = '/home/username/Documents/path/to/image/dir%s' % fileresult = []def save_image(source_image): cv2.imwrite(current_path + file , source_image) car_count.insert(0, 1) with open(path, 'rb') as fp: response = request.post( 'https://api.generate_json/', files=dict(upload=fp), headers={'Authorization': 'Token ' + 'KEY_API'}) result.append(response.json()) print(json.dumps(result, indent=2)); with open('data.json', 'w') as outfile: json.dump(result, outfile) os.remove("%s" %file) time.sleep(1)如何解決這個問題。謝謝你。
1 回答

函數式編程
TA貢獻1807條經驗 獲得超9個贊
您寫出的文件似乎保存在與您嘗試刪除的目錄不同的目錄中。這是由于os.getcwd()沒有返回尾隨/.
當您構建發送給cv2.imwrite您的路徑時,將兩條路徑連接/起來,它們之間沒有,因此您最終得到:
"/a/path/from/getcwd" + "detected_car/car99.png"
這導致看起來像這樣的路徑被發送到cv2.imwrite:
"/a/path/from/getcwddetected_car/car99.png"
但是當你去刪除文件時,你沒有指定絕對路徑,并要求os.remove刪除一個不存在的文件。
我可以想到兩種解決方法:
添加一個斜杠到current_path:
current_path = os.getcwd() + "/"
cv2.imwrite對和使用絕對路徑os.remove:
current_path = os.getcwd()
file = 'detected_car/car' + str(len(car_count)) + ".png"
temp_file = current_path + file
...
def save_image(source_image):
cv2.imwrite(temp_file , source_image)
...
os.remove("%s" %temp_file)
添加回答
舉報
0/150
提交
取消