【问题标题】:Importing a variable from another code in Python从 Python 中的另一个代码导入变量
【发布时间】:2021-09-20 14:14:07
【问题描述】:

我正在尝试将某些变量从单独的 python 代码导入到我的主代码中。单独的代码是这样的:

import cv2
import numpy as np
import os
import glob

# Defining the dimensions of checkerboard
CHECKERBOARD = (7, 9)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# Creating vector to store vectors of 3D points for each checkerboard image
objpoints = []
# Creating vector to store vectors of 2D points for each checkerboard image
imgpoints = []

# Defining the world coordinates for 3D points
objp = np.zeros((1, CHECKERBOARD[0] * CHECKERBOARD[1], 3), np.float32)
objp[0, :, :2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
prev_img_shape = None

# Extracting path of individual image stored in a given directory
images = glob.glob('./images/*.jpg')
for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Find the chess board corners
    # If desired number of corners are found in the image then ret = true
    ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD,
                                             cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE)

    """
    If desired number of corner are detected,
    we refine the pixel coordinates and display 
    them on the images of checker board
    """
    if ret == True:
        objpoints.append(objp)
        # refining pixel coordinates for given 2d points.
        corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)

        imgpoints.append(corners2)

        # Draw and display the corners
        img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2, ret)

    cv2.imshow('img', img)
    cv2.waitKey(0)

cv2.destroyAllWindows()

h, w = img.shape[:2]

"""
Performing camera calibration by 
passing the value of known 3D points (objpoints)
and corresponding pixel coordinates of the 
detected corners (imgpoints)
"""
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

print("Camera matrix : \n")
print(mtx)
print("dist : \n")
print(dist)
print("rvecs : \n")
print(rvecs)
print("tvecs : \n")
print(tvecs)

在代码的末尾,我需要将一些变量导入到我的主代码中(mtx、dist、rvecs 和 tvecs)。 当我尝试像这样导入时

from Calibration import *

或者像这样

from Calibration import mtx, tvecs, rvecs, dist

我收到此错误:

NameError: 名称“img”未定义

我怎样才能正确地做到这一点?

【问题讨论】:

  • 使用if __name__ == '__main__': 并将你想在其他文件中使用的所有变量放在它下面
  • 您确定您的问题与导入有关吗,而不是当您调用 img = cv2.imread(fname) 时该函数无法正常工作,因此 img是不是被定义了?换句话说,您的问题出在 cv2.imread 函数上?
  • @Rasputin 我怀疑这个问题更简单:根据我的回答,我认为 glob 不匹配,所以 img 稍后未设置。无论如何,为了导入一个变量需要运行很多代码。

标签: python


【解决方案1】:

你想把所有除了变量放在下面

if __name__ == "__main__":
    do_stuff

发生的情况是您的导入正在评估导入代码中的所有内容并尝试运行它,这不是您想要的。

但最佳实践是将代码的action 放在名为main 的函数中,然后在if __name__ == "__main__" 块中运行that。所以你的代码看起来像这样:

my_var = x

def my_fn():
    pass

def my_other_fn():
    pass

def main():
    my_fn()
    my_other_fn()

if __name__ == "__main__":
    main()

这边:

  • 您可以从脚本中导入变量和函数,而无需运行任何东西(很好!)
  • 您可以导入 main() 函数并从其他地方运行它(好!考虑制作例如 CLI)
  • 您可以自己运行脚本(很好!)

我们将 main() 称为入口函数(并按照约定将其命名为 main)。

__name__ 是一个特殊的变量,它等于__main__ 如果脚本是运行。有关更多详细信息,请参阅this question。所以条件__name__ == "__main__"只有在你运行脚本的时候才成立,并且你在导入变量的时候不要尝试运行其中包含的代码。

附:发生您的特定错误是因为导入脚本时没有图像./images/,因此for 块永远不会运行,因此当python 到达h, w = img.shape[:2]img 未定义。但是您根本不想运行该代码。

【讨论】:

    【解决方案2】:

    关注@GostOps@2e0byo

    将您的代码放在一个函数下并返回您要从另一个文件导入的变量。

    # Calibration.py
    
    def calibration():
        ...
        ...
        ...
    
        cv2.destroyAllWindows()
    
        h, w = img.shape[:2] 
    
        """
        Performing camera calibration by 
        passing the value of known 3D points (objpoints)
        and corresponding pixel coordinates of the 
        detected corners (imgpoints)
        """
    
        return cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) 
    
    
    if __name__ == "__main__":
        calibration()
    

    然后您可以从另一个文件导入并将其分配给那里所需的变量

    from Calibration import calibration
    
    ret, mtx, dist, rvecs, tvecs = calibration()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2020-01-15
      • 2019-05-23
      • 1970-01-01
      • 2013-06-19
      相关资源
      最近更新 更多