開始使用免費開始

狗像素百分比

解析狗狗標註資料的最後一個任務,是判斷每張影像中屬於狗(或多隻狗)的像素百分比。你需要運用本課程學到的各種技巧來計算這些資訊,並把它們加成欄位,供後續分析使用。

要計算像素百分比,先計算每隻狗所代表的像素總數,然後在同一張影像內加總。你可以用以下公式計算邊界框(bounding box):

(Xend - Xstart) * (Yend - Ystart)

注意:你可以在此情境中忽略邊界框彼此重疊的可能性。

至於百分比,計算方式為「狗像素總數」除以影像的總像素數,再乘以 100。 joined_df DataFrame 與你上次使用時相同。pyspark.sql.functions 已以 F 作為別名。

本練習屬於課程

使用 PySpark 清理資料

檢視課程

練習說明

  • 定義一個 Python 函式,接受一個由 tuple 組成的清單(狗物件),並計算每張影像的「狗」像素總數。
  • 以該函式建立 UDF,並用它在 DataFrame 上建立名為 'dog_pixels' 的新欄位。
  • 再建立另一個欄位 'dog_percent',表示影像中 'dog_pixels' 的百分比。請確保此值介於 0–100%。在指定欄位時只使用欄位名稱字串(也就是用「columnname」,不要用 df.columnname)。
  • 顯示影像中 'dog_pixels' 超過 60% 的前 10 列。請使用 SQL 風格的字串條件(也就是用 'columnname > ____')。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Calculate total pixels occupied by dogs in the image
def dogPixelCount(doglist):
  totalpixels = ____
  for dog in doglist:
    totalpixels += (dog[____] - ____[1]) * (____[____] - ____)
  return totalpixels

# Define a UDF for the pixel count
udfDogPixelCount = ____

# Add a new column 'dog_pixels' containing the pixel count for dogs in each image
joined_df = ____

# Add a column 'dog_percent' representing the percentage of the image occupied by dogs
joined_df = joined_df.____('dog_percent', (____ / (____)) * ____)

# Show the first 10 annotations with more than 60% dog
____
編輯並執行程式碼