【发布时间】: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