从一个模块的类到另一个模块的值

问题描述 投票:0回答:1

我是python的初学者,我想问一下,我有2个模块,我想将值从一个模块传递到另一个模块。我想获取“ ids”值,并在另一个模块中使用它以在屏幕上打印我试图从导入中调用它,但是它不起作用,我迷路了

Class CoordinatesGenerator:KEY_RESET = ord(“ r”)KEY_QUIT = ord(“ q”)

def __init__(self, image, output, color):
    self.output = output
    self.caption = image
    self.color = color

    self.image = open_cv.imread(image).copy()
    self.click_count = 0
    self.ids = 0
    self.coordinates = []

    open_cv.namedWindow(self.caption, open_cv.WINDOW_GUI_EXPANDED)
    open_cv.setMouseCallback(self.caption, self.__mouse_callback)

def generate(self):
    while True:
        open_cv.imshow(self.caption, self.image)
        key = open_cv.waitKey(0)

        if key == CoordinatesGenerator.KEY_RESET:
            self.image = self.image.copy()
        elif key == CoordinatesGenerator.KEY_QUIT:
            break
    open_cv.destroyWindow(self.caption)

def __mouse_callback(self, event, x, y, flags, params):

    if event == open_cv.EVENT_LBUTTONDOWN:
        self.coordinates.append((x, y))
        self.click_count += 1

        if self.click_count >= 4:
            self.__handle_done()

        elif self.click_count > 1:
            self.__handle_click_progress()

    open_cv.imshow(self.caption, self.image)

def __handle_click_progress(self):
    open_cv.line(self.image, self.coordinates[-2], self.coordinates[-1], (255, 0, 0), 1)

def __handle_done(self):
    open_cv.line(self.image,
                 self.coordinates[2],
                 self.coordinates[3],
                 self.color,
                 1)
    open_cv.line(self.image,
                 self.coordinates[3],
                 self.coordinates[0],
                 self.color,
                 1)

    self.click_count = 0

    coordinates = np.array(self.coordinates)

    self.output.write("-\n          id: " + str(self.ids) + "\n          coordinates: [" +
                      "[" + str(self.coordinates[0][0]) + "," + str(self.coordinates[0][1]) + "]," +
                      "[" + str(self.coordinates[1][0]) + "," + str(self.coordinates[1][1]) + "]," +
                      "[" + str(self.coordinates[2][0]) + "," + str(self.coordinates[2][1]) + "]," +
                      "[" + str(self.coordinates[3][0]) + "," + str(self.coordinates[3][1]) + "]]\n")

    draw_contours(self.image, coordinates, str(self.ids + 1), COLOR_WHITE)



    for i in range(0, 4):
        self.coordinates.pop()

    self.ids += 1
python opencv
1个回答
0
投票

将您的代码放入(一个名为something.py的python文件,并在同一目录中创建另一个文件,从该位置调用printer.py,您将这样导入(something.py)模块:

from something.py import CoordinatesGenerator

[别忘了在文件夹中放置一个名为__init__.py的文件,以便python可以使用它。否则,您的导入将失败!

结论:您尝试导入模块的每个文件夹都需要一个__init__.py文件。因此,在上面的示例中,您将有一个包含3个文件的文件夹

© www.soinside.com 2019 - 2024. All rights reserved.