python - Python - 计算图像平均颜色的最快方法
问题描述
我正在尝试编写一个脚本来每秒从电影中获取一帧的平均颜色。目前我正在使用 Pillows resize() 函数执行此操作,但是它非常慢(每秒 5-10 帧),这意味着分析整部电影需要几个小时。这是我写的代码:
def analyse_frames(movie_path):
try:
with open(MOVIE_TITLE, "w") as file:
counter = 0
video = cv2.VideoCapture(movie_path)
total_seconds = int(video.get(
cv2.CAP_PROP_FRAME_COUNT)/video.get(cv2.CAP_PROP_FPS))
succeeded, frame = video.read()
while succeeded:
video.set(cv2.CAP_PROP_POS_MSEC, (counter*1000))
succeeded, frame = video.read()
img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(img).resize((1, 1))
color = str(img_pil.getpixel((0, 0)))[1:-1]
file.write((str(color) + "\n"))
counter += 1
succeeded = counter <= total_seconds
print(f"Frames analyzed: {counter} / {total_seconds}")
except:
print("Couldn't read movie file.")
有谁知道计算这个平均值的更快方法?任何帮助,将不胜感激!
解决方案
frame.mean(axis=(0,1))
假设它是一个 3 通道 numpy 数组,则为您提供该帧的平均 BGR(或 RGB)值。
推荐阅读
- amazon-web-services - 来自 AWS RDS 的数据是否存储在 Amazon S3 上?
- scala - 使用类型构造函数定义函数签名以禁止某些数据类型
- sql - 如何将 Raspberry Pi SenseHat 数据导入 azure sql server
- reactjs - 如果滚动在 div 内,则检测滚动
- text-mining - 为什么 clean.text() 函数会改变词频?
- windows - 如果未调用 `cmd`,批处理文件 `start` 命令将失败
- git - Git 因致命错误而失败 - 无法读取用户名终端提示已禁用
- apache - 从外部应用程序到 apache httpd Web 服务器的 httpS 调用问题
- r - R Shiny 中的嵌套 dq_accordion 菜单
- google-apps-script - 如何使用 Google 脚本将名称插入公式?