I'm learning opencv and to make it easy for me to not have to scroll through hundreds of lines of code, I've made two files named file1.py and file2.py.
All the functions I want to use are in file1.py and I'm calling them from file2.py. Functions in file1.py are:
def main(title="Test", func=None):
global img, original_img
cv2.namedWindow(title)
cv2.setMouseCallback(title, func)
while True:
cv2.imshow(title, img)
if func == draw_shape:
k = cv2.waitKey(1)
if k == ord('m') or k == ord('M'):
shape = not shape
elif k == 27:
break
else:
if cv2.waitKey(1) == 27:
break
cv2.destroyWindow(title)
def draw_shape(event, x, y, flags, param):
global ix, iy, shape, drawing, fill, img, original_img
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
if shape:
cv2.rectangle(img, (ix, iy), (x, y), (0, 244, 0), fill)
elif not shape:
cv2.circle(img, (x, y), 20, (0, 0, 244), fill)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
img = deepcopy(original_img)
There's a lot more code having same problem (which I'll explain in a moment) in file1.py which I omitted for sake of space.
I know I can modify main() and pass img to it but the problem starts at draw_shape() which is associated with cv2.setMouseCallback and gets called automatically. So I can't just pass variables, like ix, drawing etc. which, when I was calling main() in file1.py itself, were global in that case, to draw_shape() myself.
But now as I've made file2.py and I want to call main() from there, I'm not able to pass those variables anymore.
The code in file2.py is as:
from file1 import main, draw_shape
if __name__ == "__main__":
imagepath = "some\path\someImage.jpg"
img = cv2.imread(imagepath, 0)
original_img = deepcopy(img)
ix, iy, fill = (-1, -1, 0)
shape, drawing = True, False
main(title='XYZ', func=draw_shape)
Any suggestions how I could make main() and draw_shape() to use variables, I've declared by the same names as required by them, from file2.py (or if any other way to pass variables to them)?