我有一个工作程序,尽管工作可能被夸大了。我想优化代码,我使用了for循环来求和屏幕的红色,绿色和蓝色像素值。
我以前尝试过沿第二个轴求和,但无济于事。因此,任何其他提示都将有所帮助。如果需要,我也打算使用其他库。
import numpy as np
from PIL import ImageGrab
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
colors = ['red', 'lime', 'blue']
explode = (0.01, 0.01, 0.01)
labels = ['Red', 'Green', 'Blue']
nums = [0, 0, 0]
fig, ax = plt.subplots()
def update(num):
ax.clear()
ax.axis('equal')
str_num = str(num)
nums = [0, 0, 0]
screen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
for x in range ((1079)):
for y in range ((1919)):
nums[0] += screen[x][y][0]
nums[1] += screen[x][y][1]
nums[2] += screen[x][y][2]
ax.pie(nums, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
ax.set_title(str_num)
ani = FuncAnimation(fig, update, repeat=False)
plt.show()
我希望我的时间至少会有一点改善。目前,加载新帧大约需要7或8秒钟,但是我对3到4以下的值感到满意。
答案 0 :(得分:0)
由于screen
变量是一个NumPy数组,因此不需要for循环。您可以直接将总和作为
def update(num):
ax.clear()
ax.axis('equal')
str_num = str(num)
nums = [0, 0, 0]
screen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080)))
# This should work too:
# nums = np.sum(screen, axis=(1,2))
nums[0] = np.sum(screen[:,:,0])
nums[1] = np.sum(screen[:,:,1])
nums[2] = np.sum(screen[:,:,2])
ax.pie(nums, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
ax.set_title(str_num)