世界! 我有这个代码:
from numpy import array
from cv2 import imshow, cvtColor, imwrite, imread, destroyAllWindows, COLOR_BGR2RGB
from pyscreenshot import grab
import pytesseract
filename = 'image.png'
elements_for_replace = {'iL': '1L', 'Bi': 'B1', 'Bl': 'B1', 'Ci': 'C1', 'Cl': 'C1'}
pytesseract.pytesseract.tesseract_cmd = r'C:\Users\Administrator\AppData\Local\Tesseract-OCR\tesseract.exe'
def scanning(x1, y1, x2, y2):
screen = array(grab(bbox=(x1, y1, x2, y2)))
imwrite(filename, screen)
img = imread(filename)
text = pytesseract.image_to_string(img)
history = text.split()
return history
def first():
return scanning(730, 740, 1335, 790)
def second():
return scanning(730, 453, 1335, 500)
def third():
return scanning(817, 45, 1522, 99)
def replace_elements(data, replace_data):
for item in data:
if item in replace_data:
data[data.index(item)] = replace_data[item]
return data
def get_data():
x = replace_elements(first(), elements_for_replace)
y = replace_elements(second(), elements_for_replace)
z = replace_elements(third(), elements_for_replace)
destroyAllWindows()
return x, y, z
当调用函数 get_data() 时,此代码使用计算机视觉在屏幕上的三个不同位置将图像转换为文本。始终如一地做到这一点。然后它用正确的元素替换失败的元素。在输出中,我们得到一个列表元组 (x, y, z),它将由程序的另一部分处理。
将图像转换为文本需要花费大量时间。而程序的顺序执行这次乘以3。我得出的结论是我需要使用multiprocessing模块(或者更确切地说concurrent.futures)来减少程序执行时间。
我重写了函数 get_data(),如下所示:
import concurrent.futures
def get_data():
with concurrent.futures.ProcessPoolExecutor() as executor:
x = executor.submit(replace_elements, first(), elements_for_replace)
y = executor.submit(replace_elements, second(), elements_for_replace)
z = executor.submit(replace_elements, third(), elements_for_replace)
destroyAllWindows()
return x, y, z
现在返回的变量具有数据类型
如何开始并行执行函数,使函数的返回值与第一个版本的代码相同,即
最佳答案
executor.submit()
returns a Future object ,而不是调用的函数的值。为了获取函数返回的值,必须调用 result()在 Future 对象上。在您的情况下,您需要像这样修改代码:
def get_data():
with concurrent.futures.ProcessPoolExecutor() as executor:
future_x = executor.submit(replace_elements, first(), elements_for_replace)
future_y = executor.submit(replace_elements, second(), elements_for_replace)
future_z = executor.submit(replace_elements, third(), elements_for_replace)
destroyAllWindows()
# Actually get the value of the function here
x = future_x.result()
y = future_y.result()
z = future_z.result()
return x, y, z
此外,作为建议,您还可以考虑使用 ProcessPoolExecutor.map()稍微清理一下代码。有了它,您就不必定义每个结果。
关于python - 如果我使用多处理,函数返回值类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75793631/