簡體   English   中英

如何在 Python 中設置圖像路徑

[英]How to set Image path in Python

我有下面的 python 代碼,它選擇 python 文件的同一目錄中的所有圖像並將它們散列以接收 hash txt 文件。 我寧願只設置所需的圖像,而不是 hash 所有圖像。 你能告訴我如何以及在哪里可以設置圖像的名稱或路徑? (例如:至 hash 僅以下圖像 C:\Users\admin\Desktop\TD\image.png)

代碼如下:

import os
import hashlib
import logging

logging.basicConfig(filename='InitializationHash.txt', level=logging.INFO,
                    format='%(message)s')

image_ext = ['.png', '.jpg']

def hash_image(filepath):
    with open(filepath, 'rb') as f:
        file_bytes = f.read()
        hash_text = hashlib.sha256(file_bytes).hexdigest()
        logging.info(hash_text)

def get_images(path):
    for f in os.listdir(path):
        full_path = os.path.join(path, f)
        if os.path.isdir(full_path):
            get_images(full_path)
        else:
            ext = os.path.splitext(full_path)[1]
            if ext in image_ext:
                hash_image(full_path)
if __name__ == '__main__':
   get_images(".")

如果你試圖傳遞一個文件的名稱並且只有 hash 這個文件你可以像這樣創建一個新的 function

def get_one_image(file_Name):
    filepath = os.path.abspath(file_Name)
    hash_image(filepath)

你可以改為調用它

if __name__ == '__main__':
   get_one_image("FileName.png")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM