2017-02-09 38 views
1

我是新編程並嘗試製作圖像縮放器。我想在文件名之前讓用戶編寫自定義前綴。尺寸也是可以定製的。cv2.resize()錯誤:使用不同的名稱保存相同的圖片

cv2.imshow()工作正常,但cv2.resize()沒有。如果使用imshow檢查它,儘管有for循環,它只顯示一張圖片,然後cv2.imwrite只保存一張帶有所有選定圖片名稱的圖片。 列表似乎沒有問題。

我希望我是清楚的,代碼:

def openfiles(): 

    global picture_original 
    global file_path 
    global f 

    # Valid filetypes 
    file_types=[("Jpeg files","*.jpg"),("PNG files","*.png"),("BMP files","*.bmp"),("all files","*.*")] 

    window.filenames = filedialog.askopenfilenames(initialdir = "/",title = "Select file",filetypes = (file_types)) # TUPLE of filepath/filenames 

    #f = [] 

    # Creating a list from the tuple 
    for pics in window.filenames: 
     f.append(pics) 

     f = [picture.replace('/', "\\") for picture in f] 

    try: 
     for picture in f: 
      picture_original = cv2.imread(picture, 1) 
      #cv2.imshow("Preview", picture_original) 
      #cv2.waitKey(1) 
    except: 
     msgbox_openerror() # Error opening the file 

    # Getting the filepath only from the list "f": 
    file_path = f[0].rsplit("\\",1)[0] 
    view_list() 

def save_command(): 
    """ 
    function to save the resized pictures 
    """ 
    global picture_resized 
    global prefix 
    prefix = "Resized_" 
    lst_filename = [] 
    lst_renamed = [] 

    for i in f: 
     #print(f) 
     path,filename = os.path.split(i) # path - only filepath | filename - only filename with extension 
     lst_filename.append(prefix+filename) 

    for i in range(len(f)): 
     lst_renamed.append(os.path.join(path, lst_filename[i])) 

    for i in range(len(f)): 
     picture_resized = cv2.resize(picture_original, ((int(width.get())), int(height.get()))) 
     cv2.imshow("Preview", picture_resized) 
     cv2.waitKey(1) 

    for i in lst_renamed: 
     cv2.imwrite(i, picture_resized) 

我希望有人有一些想法。先謝謝你!

+0

你有什麼期望在'openfiles()'完成後包含'picture_original'? –

+0

或'picture_resized' ......循環中沒有什麼能夠根據「i」的值調整大小 - 所以你基本上一次又一次地在相同的輸入上重複相同的操作。同樣,在使用'imwrite'的循環中,唯一改變的是文件名。 |如果您有多個文件名要處理(並將它們存儲在列表中),則還應該有多個圖像(並將它們存儲在列表中)。 –

+1

我期望'picture_original'和'picture_resized'應該是numpy數組的列表。他們的類型應該是 是的,你可能是正確的與循環相關的。我嘗試調整'picture_original [i]'和'imwrite'。 – koger23

回答

0

這是一個例子乘以比率來調整,並且將您的圖像

def ResizeImage(filepath, newfileName,ratio): 
     image = cv2.imread(filepath)   #Open image 
     height, width = image.shape[:2]  #Shapes 
     image2 = cv2.resize(image, (width/ratio, height/ratio), interpolation = cv2.INTER_AREA) 
     cv2.imwrite(newfileName,image2)   #saves, True if OK 
     return filepath 

所以,如果你

image = "originalpath" 
resized = ResizeImage(image,"Resized_"+image,2) 
newImage = cv2.imread(resized) 
cv2.imshow("new",newImage) 
cv2.waitKey(1) 

你應該讓你的圖片一半大小

+0

你的回答是部分正確的,但是如果他們試圖按照「原樣」運行你的代碼,它還不能作爲其他例子。請閱讀問題OP再次結合註釋a nd相應地修改你的答案,直到完整的工作答案。只有這樣你才能得到我的最高票數。審查結束。 – ZF007

相關問題