cv2.resize()错误:使用不同的名称

时间:2017-02-09 18:56:02

标签: python opencv cv2

我是编程新手并尝试制作图像缩放器。我希望能够在文件名之前由用户编写自定义前缀。尺寸也是惯例。

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)

我希望有人有一些想法。提前谢谢!

1 个答案:

答案 0 :(得分: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)

您应该将图片调整为一半