Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有效地从字符串中每隔n个字符获取n个字符_Python_Python 2.7 - Fatal编程技术网

Python 有效地从字符串中每隔n个字符获取n个字符

Python 有效地从字符串中每隔n个字符获取n个字符,python,python-2.7,Python,Python 2.7,我正在处理一个包含rgba图像的字符串(每个通道8位),因此该字符串的每四个字符是一个像素,每个字符是该像素的一个通道,例如: #4x4 pixel image img_str = 'rgbargbargbargba' 现在想象一幅更大的图像,使用以下方法提取alpha通道非常快: img_str_a = img_str[3::4] # result applying this to the 4x4 image would be 'aaaa' 对于1350x765图像,这将在大约2ms内执行

我正在处理一个包含rgba图像的字符串(每个通道8位),因此该字符串的每四个字符是一个像素,每个字符是该像素的一个通道,例如:

#4x4 pixel image
img_str = 'rgbargbargbargba'
现在想象一幅更大的图像,使用以下方法提取alpha通道非常快:

img_str_a = img_str[3::4]
# result applying this to the 4x4 image would be 'aaaa'
对于1350x765图像,这将在大约2ms内执行。但现在我需要提取RGB通道,以类似“rgbrgbrgbrgb”的字符串结尾,带有4x4图像。我试过这个:

img_str_rgb = ''.join('' if i%4 == 0 else char for i, char in enumerate(img_str, 1))

这是可行的,但对于相同的1350x765图像,需要大约700毫秒。这太多了,因为我正在处理视频,所以我需要的时间要少得多。

与其加入单个字符,不如加入子字符串:

img_str_rbg = ''.join(img_str[j:j+3] for j in xrange(0, len(img_str), 4))
甚至更快,您可以使用
zip
,或者python2
izip

from itertools import izip, imap
img_str_rgb = ''.join(imap(''.join, izip(img_str[0::4], img_str[1::4], img_str[2::4])))
对于您的场景,
numpy
更好:

import numpy as np
img = np.fromstring(img_str,dtype=np.byte).reshape(765,1350,4)
img_alpha = img[:, :, 3]
img_rgb = img[:, :, :3]

为什么不使用
numpy
?更多的输入和预期的输出将有助于理解您正在尝试做什么。嗨,丹尼尔,我没有尝试使用numpy,我将做一些测试。感谢您的快速回答,但这仍然需要太多时间(1350x765图像大约需要220毫秒)我需要5毫秒左右,不知道这是否可能。然后使用
numpy
。谢谢!Numpy要快得多。