如何解决数组创建太慢
我正在尝试从头开始创建图像阵列。 我运行了代码,但是运行它大约需要30秒。 我觉得使用numpy本机函数可能会更快。 我该怎么办?
import cv2
import numpy as np
import time
volumes = np.random.randint(low=0,high=200,size=10000)
print(volumes)
image_heigh = 128
image_width = 256
image_channel = 3
show_img = False
def nomralized(data,data_min,data_max,maximum_value):
nomamized_data = maximum_value * ((data - data_min) / (data_max - data_min))
return nomamized_data
start_time = time.time()
for ii in range(len(volumes)-image_width):
# ===================== part to optimize start
final_image = np.zeros((image_heigh,image_width,image_channel))
start = ii
end = ii + image_width
current_vols = volumes[start:end]
# nomalize data
vol_min = 0
vol_max = np.max(current_vols)
vol_norm = nomralized(data=current_vols,data_min=vol_min,data_max=vol_max,maximum_value=image_heigh)
for xxx in range(image_width):
final_image[:int(vol_norm[xxx]),xxx,:] = 1
# ===================== part to optimize end
if show_img:
image = np.float32(final_image)
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
cv2.imshow("ok",image)
cv2.waitKey(27)
print("total running time: ",(time.time() - start_time))
如何使该图像阵列的创建速度更快? 我需要在每个时间步创建图像,因为我想模拟每个新时间步出现的真实实时数据流。
这就是为什么我只想优化这段代码的原因:
for xxx in range(image_width):
final_image[:int(vol_norm[xxx]),:] = 1
我该怎么做?
解决方法
接下来最简单的优化是
- 使用比较值与
np.arange(...)
而不是内部循环。 - 使用灰色图像代替3通道RGB。数据处理量减少了3倍。
- 使用np.uint8类型而不是np.float32,它处理起来速度更快,并且无需转换为float32即可进行CV2可视化。
以上所有这些优化均可以极大地提高速度(10x
次,而我的运行时间是2.6 sec
,而不是之前的27 sec
。
另一个我没有做的非常有用的优化是,在当前窗口内整个数据的最大值/最小值不变的情况下,您无需重新计算以前的图像像素。仅当最大/最小更改时,才需要重新计算以前的图像数据。而且我希望您的现实生活中的数据会像外汇或比特币价格一样在逐渐变化,因此窗口中的最大/最小变化很少。
上面提到的优化1)-3)在下一个代码中实现:
import cv2
import numpy as np
import time
volumes = np.random.randint(low=0,high=200,size=10000)
print(volumes)
image_heigh = 128
image_width = 256
image_channel = 3
show_img = False
def nomralized(data,data_min,data_max,maximum_value):
nomamized_data = maximum_value * ((data - data_min) / (data_max - data_min))
return nomamized_data
start_time = time.time()
aranges = np.arange(image_heigh,dtype = np.int32)[:,None]
for ii in range(len(volumes)-image_width):
# ===================== part to optimize start
#final_image = np.zeros((image_heigh,image_width,image_channel),dtype = np.float32)
start = ii
end = ii + image_width
current_vols = volumes[start:end]
# nomalize data
vol_min = 0
vol_max = np.max(current_vols)
vol_norm = nomralized(data=current_vols,data_min=vol_min,data_max=vol_max,maximum_value=image_heigh)
final_image = (aranges < vol_norm[None,:].astype(np.int32)).astype(np.uint8) * 255
# ===================== part to optimize end
if show_img:
cv2.imshow('ok',final_image)
cv2.waitKey(27)
print("total running time: ",(time.time() - start_time))
对于上面的代码,我只是对内部循环进行了一次优化,从而使代码的速度甚至提高了2x
倍,从而使时序达到1.3 sec
。但是我还放回了3个通道和float32,这降低了速度,导致最终的2.8 sec
,here is the code
如果不需要重新计算旧图像数据,则可以进行另一个下一个优化。
要优化的主要事情是,您在每一步上都重新计算了几乎相同的整个图像,沿宽度方向偏移了1个像素。取而代之的是,您只需要计算整个图像一次,然后向右移动而不是1个像素,而是向右移动整个图像宽度。
此优化运行时间之后为0.08 sec
。
并且仅为了显示动画而不是为了计算图像数据而执行1像素步进,如果需要速度,则应该仅对图像数据进行一次计算。
import cv2
import numpy as np
import time
volumes = np.random.randint(low=0,size=10000)
print(volumes)
image_heigh = 128
image_width = volumes.size #256
image_channel = 3
screen_width = 256
show_img = False
def nomralized(data,maximum_value):
nomamized_data = maximum_value * ((data - data_min) / (data_max - data_min))
return nomamized_data
start_time = time.time()
for ii in range(0,len(volumes),image_width):
# ===================== part to optimize start
final_image = np.zeros((image_heigh,image_channel))
start = ii
end = ii + image_width
current_vols = volumes[start:end]
# nomalize data
vol_min = 0
vol_max = np.max(current_vols)
vol_norm = nomralized(data=current_vols,maximum_value=image_heigh)
for xxx in range(image_width):
final_image[:int(vol_norm[xxx]),xxx,:] = 1
# ===================== part to optimize end
if show_img:
for start in range(0,final_image.shape[1] - screen_width):
image = np.float32(final_image[:,start : start + screen_width])
image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
cv2.imshow("ok",image)
cv2.waitKey(27)
print("total running time: ",(time.time() - start_time))
我还根据您的数据创建了动画图像:
如果要创建相同的动画,只需将下一段代码附加到上面脚本的末尾:
# Needs: python -m pip install pillow
import PIL.Image
imgs = [PIL.Image.fromarray(final_image[:,start : start + screen_width].astype(np.uint8) * 255) for start in range(0,final_image.shape[1] - screen_width,6)]
imgs[0].save('result.png',append_images = imgs[1:],save_all = True,lossless = True,duration = 100)
我还实现了实时实时流数据渲染/可视化的仿真。
-
live_stream()
生成器会在随机的时间点吐出随机数量的数据,这是为了模拟数据生成过程。 -
stream_fetcher()
收听实时流,并将接收到的所有数据记录到python队列q0
中,此提取程序在一个线程中运行。 -
renderer()
获取提取程序记录的数据,并通过您的数学公式和规范化过程将其渲染为图像,它渲染尽可能多的数据,从而导致图像的宽度不同,渲染的图像保存到另一个队列{{ 1}}。 -
q1
通过获取尽可能多的渲染图像来可视化渲染数据。
所有功能都在单独的线程中运行,不会阻塞整个过程。另外,如果有任何线程在减慢速度,那么它将跳过一些数据以赶上当前的实时数据,因此每个队列都不会溢出。
您还可能会看到可视化过程是快速的,这不是因为功能有些慢,而是因为实时流在每个时间步中吐出不同数量的数据,所以这通常是实时数据的行为。
>在接下来的代码中,我还做了前面提到的额外优化,如果min / max不变,则不会重新计算图像。
visualizer()
上面的实时过程仿真被渲染到import cv2,numpy as np
import time,random,threading,queue
image_height = 256
image_width = 512
# Make results reproducible and deterministic
np.random.seed(0)
random.seed(0)
def live_stream():
last = 0.
while True:
a = np.random.uniform(low = -1.,high = 1.,size = random.randint(1,20)).astype(np.float64).cumsum() + last
yield a
last = a[-1]
time.sleep(random.random() * 0.1)
q0 = queue.Queue()
def stream_fetcher():
for e in live_stream():
q0.put(e)
threading.Thread(target = stream_fetcher,daemon = True).start()
aranges = np.arange(image_height,None]
q1 = queue.Queue()
def renderer():
def normalized(data,maximum_value):
nomamized_data = maximum_value * ((data - data_min) / (data_max - data_min))
return nomamized_data
prev_image = np.zeros((image_height,0),dtype = np.uint8)
prev_vols = np.zeros((0,),dtype = np.float64)
while True:
data = []
data.append(q0.get())
try:
while True:
data.append(q0.get(block = False))
except queue.Empty:
pass
vols = np.concatenate(data)[-image_width:]
prev_vols = prev_vols[-(image_width - vols.size) or prev_vols.size:]
concat_vols = np.concatenate((prev_vols,vols))[-image_width:]
vols_min,vols_max = np.amin(concat_vols),np.amax(concat_vols)
if prev_vols.size > 0 and (vols_min < np.amin(prev_vols) - 10 ** -8 or vols_max > np.amax(prev_vols) + 10 ** -8):
vols = concat_vols
prev_image = prev_image[:,:-prev_vols.size]
prev_vols = prev_vols[:0]
vols_norm = normalized(
data = vols,data_min = vols_min,data_max = vols_max,maximum_value = image_height,)
image = (aranges < vols_norm.astype(np.int32)[None,:]).astype(np.uint8) * 255
whole_image = np.concatenate((prev_image,image),axis = 1)[:,-image_width:]
q1.put(whole_image)
prev_image = whole_image
prev_vols = concat_vols
threading.Thread(target = renderer,daemon = True).start()
def visualizer():
imgs = []
while True:
data = []
data.append(q1.get())
try:
while True:
data.append(q1.get(block = False))
except queue.Empty:
pass
image = np.concatenate(data,-image_width:]
cv2.imshow('ok',image)
cv2.waitKey(1)
if imgs is not None:
try:
# Needs: python -m pip install pillow
import PIL.Image
has_pil = True
except:
has_pil = False
imgs = None
if has_pil:
imgs.append(PIL.Image.fromarray(np.pad(image,((0,(image_width - image.shape[1],0)),constant_values = 0)))
if len(imgs) >= 1000:
print('saving...',flush = True)
imgs[0].save('result.png',duration = 100)
imgs = None
print('saved!',flush = True)
threading.Thread(target = visualizer,daemon = True).start()
while True:
time.sleep(0.1)
中,我在下面显示:
我还决定通过使用更高级的result.png
而非matplotlib
来改善可视化,以显示轴并进行实时绘图。可视化图像如下:
下一个是基于matplotlib的代码,与上面的最后一个图像相对应:
cv2
然后我决定使用RGB调色板播放最后一张彩色图像,峰值越高,红色越偏红;如果中间越多,则绿色越偏红;足够低,则它会偏蓝。下面的结果图像是通过this coloring code实现的:
下面还有另一种彩色动画,在this code的帮助下,以线条样式而不是条形样式出现:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。