狗像素百分比
解析狗的标注数据的最后一步,是确定每张图像中表示狗(或多只狗)的像素所占百分比。您需要运用本课程中学到的各种技巧来计算这些信息,并将其添加为列,便于后续分析。
若要计算像素百分比,先计算每只狗所代表的像素总数,然后在图像级别求和。您可以使用以下公式计算边界框:
(Xend - Xstart) * (Yend - Ystart)
注意:在本题中,您可以忽略边界框重叠的可能性。
对于百分比,计算总的"dog"像素数除以图像的总大小,再乘以 100。
joined_df DataFrame 与您上次使用时一致。pyspark.sql.functions 已起别名为 F。
本练习是课程的一部分
使用 PySpark 进行数据清洗
练习说明
- 定义一个 Python 函数,接收一个元组列表(狗对象),计算每张图像中的"dog"像素总数。
- 基于该函数创建一个 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
____