0

次のように、ラベルで分割された GCloud バケットが既にあります。

gs://my_bucket/dataset/label1/
gs://my_bucket/dataset/label2/
...

各ラベル フォルダーには、写真が含まれています。ここで説明されているように、必要な CSV を生成したいのですが、各フォルダーに何百もの写真があることを考えると、プログラムでそれを行う方法がわかりません。CSV ファイルは次のようになります。

gs://my_bucket/dataset/label1/photo1.jpg,label1
gs://my_bucket/dataset/label1/photo12.jpg,label1
gs://my_bucket/dataset/label2/photo7.jpg,label2
...
4

2 に答える 2

2

データセット フォルダー内のすべてのファイルを完全なパスで一覧表示し、それを解析してファイルを含むフォルダーの名前を取得する必要があります。この場合、これが使用するラベルです。これは、いくつかの異なる方法で行うことができます。コードのベースとなる 2 つの例を示します。

Gsutil にはバケットの内容を一覧表示するメソッドがあり、bash スクリプトを使用して文字列を解析できます。

 # Create csv file and define bucket path
bucket_path="gs://buckbuckbuckbuck/dataset/"
filename="labels_csv_bash.csv"
touch $filename

IFS=$'\n' # Internal field separator variable has to be set to separate on new lines

# List of every .jpg file inside the buckets folder. ** searches for them recursively.
for i in `gsutil ls $bucket_path**.jpg`
do
        # Cuts the address using the / limiter and gets the second item starting from the end.
        label=$(echo $i | rev | cut -d'/' -f2 | rev)
        echo "$i, $label" >> $filename
done

IFS=' ' # Reset to originnal value

gsutil cp $filename $bucket_path

また、さまざまな言語用に提供されているGoogle Cloud クライアント ライブラリを使用して実行することもできます。Python を使用した例を次に示します。

# Imports the Google Cloud client library
import os
from google.cloud import storage

# Instantiates a client
storage_client = storage.Client()

# The name for the new bucket
bucket_name = 'my_bucket'
path_in_bucket = 'dataset'

blobs = storage_client.list_blobs(bucket_name, prefix=path_in_bucket)

# Reading blobs, parsing information and creating the csv file
filename = 'labels_csv_python.csv'
with open(filename, 'w+') as f:
    for blob in blobs:
        if '.jpg' in blob.name:
            bucket_path = 'gs://' + os.path.join(bucket_name, blob.name)
            label = blob.name.split('/')[-2]
            f.write(', '.join([bucket_path, label]))
            f.write("\n")

# Uploading csv file to the bucket
bucket = storage_client.get_bucket(bucket_name)
destination_blob_name = os.path.join(path_in_bucket, filename)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(filename)
于 2019-11-06T08:25:30.200 に答える