简体   繁体   中英

os.makedirs not working with tkinter? Not sure what's going wrong

I have a program that generates images that are saved to a directory that is created everytime it runs. The program works fine when I run it through the command line but when I run it throuh a tkinter button, it doesn't seem to create the directory. The program also outputs a log file but that seems to work. Apparently the code executes as I figured out by some old fashioned print statement debugging. Any ideas on why this might be? Here is the function:

def compareImages(self,img1, img2, image_name):
        diff = cv2.absdiff(img1, img2)
        mask = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

        th = 1
        imask =  mask>th
    
        canvas = np.zeros_like(img2, np.uint8)
        canvas[imask] = img2[imask]
        
        dirname = "IMAGE_RESULTS_"+CURR_TIME
        
        Utils().make_dir(PATH, dirname)
        print("image where?")
        cv2.imwrite(dirname+"/result"+CURR_TIME+"_"+image_name+".png", canvas)
        

The cv2.imwrite(dirname+"/result"+CURR_TIME+"_"+image_name+".png", canvas) line is what I use to create the image. The tkinter code is as follows:

def run_image_analysis():
    run_image_analysis.main().  

button1 = Button(root,text="run image analysis",command= run_image_analysis)
button1.pack()

The code for the make_dir function is here:


def make_dir(self, dirname, parent_dir):  
        path = os.path.join(parent_dir, dirname) 
        os.makedirs(path, exist_ok=True) 

By playing around I found that running:

        cv2.imwrite(result"+CURR_TIME+"_"+image_name+".png", canvas)

actually works with tkinter. So apparently the new directory "dirname" referred to in the original code is not being created by makedir. What exactly is going on here? What confuses me is it works when I run it normally but not when I run it through tkinter.

make_dir joins two path components to create a path for mkdirs . This method should return its constructed path to be used by the rest of the program.

def make_dir(self, dirname, parent_dir):  
        path = os.path.join(parent_dir, dirname) 
        os.makedirs(path, exist_ok=True) 
        return path

Then change the callers

def compareImages(self,img1, img2, image_name):
        diff = cv2.absdiff(img1, img2)
        mask = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

        th = 1
        imask =  mask>th
    
        canvas = np.zeros_like(img2, np.uint8)
        canvas[imask] = img2[imask]
        
        dirname = "IMAGE_RESULTS_"+CURR_TIME
        
        target_dir = Utils().make_dir(PATH, dirname)
        print("image where?")
        cv2.imwrite(os.path.join(target_dir, "/result"+CURR_TIME+"_"+image_name+".png"),
                canvas)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM