Python for循环和条件中的多处理?

Python for循环和条件中的多处理?,python,multiprocessing,Python,Multiprocessing,我有一个图像列表(称为屏幕),我正在拍摄当前窗口的屏幕截图,然后将OpenCV中的此屏幕截图与列表进行比较,以了解打开了哪个屏幕。我用for循环来做这个,但是一次比较一个图像会使我的软件速度变慢。所以,我转向了多重处理。下面是它的代码: def cpu_bound(template): for i in range(len(screens)): #compare_images is function to find similarity result= c

我有一个图像列表(称为
屏幕
),我正在拍摄当前窗口的屏幕截图,然后将OpenCV中的此屏幕截图与列表进行比较,以了解打开了哪个屏幕。我用for循环来做这个,但是一次比较一个图像会使我的软件速度变慢。所以,我转向了多重处理。下面是它的代码:

def cpu_bound(template):
    for i in range(len(screens)):
        #compare_images is function to find similarity
        result= compare_images(screen[i],template)
        if result is True:
            return i
    return -1

def find_screen(template):
        with multiprocessing.Pool() as pool:
            i=pool.map(cpu_bound, template)
            return i
为了
find_screen
我正在传递屏幕截图,但在多处理过程中,我得到一个错误,输入图像在这一行上没有相同的尺寸:

result= compare_images(screens[i],template)

尽管没有多重处理的循环运行良好。在实现多处理时我犯了什么错误?

您试图将函数(
cpu绑定的
)映射到单个值(
模板
)上,函数本身执行循环(在所有
屏幕
)。那是行不通的

相反,直接使用
比较\u图像

with multiprocessing.Pool() as pool:
    result = pool.map(lambda screen: compare_images(screen, template), screens)

您正试图将一个函数(
cpu\u-bound
)映射到单个值(
template
)上,并且函数本身执行循环(在所有
屏幕上)。那是行不通的

相反,直接使用
比较\u图像

with multiprocessing.Pool() as pool:
    result = pool.map(lambda screen: compare_images(screen, template), screens)

你应该一个接一个地去游泳。这里有一个例子

from multiprocessing import Pool
from functools import partial

def func(x, found):
    if x == found:
        return True
    else: 
        return False

if __name__ == '__main__':
    asd = [1, 2, 3]
    to_be_found = 3
    f = partial(func, to_be_found)
    with Pool() as p:
        print(p.map(f, asd))

你应该一个接一个地去游泳。这里有一个例子

from multiprocessing import Pool
from functools import partial

def func(x, found):
    if x == found:
        return True
    else: 
        return False

if __name__ == '__main__':
    asd = [1, 2, 3]
    to_be_found = 3
    f = partial(func, to_be_found)
    with Pool() as p:
        print(p.map(f, asd))

看来你是从另一个角度得到的。获取一个函数和一个iterable,并在iterable的每个元素上运行该函数。但是您正在将
模板
图像作为iterable传递,因此出现了这个奇怪的错误。你可能想做:

i = pool.map(cpu_bound, screens) 
这将需要您稍微更改
cpu\u绑定的

def cpu_绑定(屏幕):
#比较图像是发现相似性的函数
结果=比较图像(屏幕、模板)
如果结果为真:
返回屏幕
返回-1

这是假设您正在使用全局变量。如果不是这样,您可以使用来传递多个参数<代码>cpu绑定
将为:

def cpu_bound(screen, template):
    ...
你可以称之为:

从itertools导入重复
...
i=pool.starmap(cpu绑定,zip(屏幕,重复(模板)))

看来你是从另一个角度得到的。获取一个函数和一个iterable,并在iterable的每个元素上运行该函数。但是您正在将
模板
图像作为iterable传递,因此出现了这个奇怪的错误。你可能想做:

i = pool.map(cpu_bound, screens) 
这将需要您稍微更改
cpu\u绑定的

def cpu_绑定(屏幕):
#比较图像是发现相似性的函数
结果=比较图像(屏幕、模板)
如果结果为真:
返回屏幕
返回-1

这是假设您正在使用全局变量。如果不是这样,您可以使用来传递多个参数<代码>cpu绑定
将为:

def cpu_bound(screen, template):
    ...
你可以称之为:

从itertools导入重复
...
i=pool.starmap(cpu绑定,zip(屏幕,重复(模板)))

道歉。修正了缩进。什么是
模板
屏幕
?请发布某种形式的帮助模板,以便我们能够有效地帮助模板是当前窗口的截图,屏幕是列表,我正在将截图与之进行比较,以找到相似之处抱歉。修正了缩进。什么是
模板
屏幕
?请发布一些形式的帮助模板,以便我们能够有效地帮助模板是当前窗口的截图,屏幕是列表,我正在将截图与之进行比较,以找到相似之处。非常感谢,这很有效。救了我一天!!!非常感谢,这起作用了。救了我一天!!!