繁体   English   中英

类型错误:预期的 Ptr<cv::umat> 对于参数 'm'</cv::umat>

[英]TypeError: Expected Ptr<cv::UMat> for argument 'm'

我使用以下代码通过 Tkinter 中的 OpenCV 打开和保存图像:

def select_image():
    fln = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select image file", filetypes=(("JPG File","*.jpg"), ("PNG file", "*.png"), ("All Files", "*.*")))
    img = Image.open(fln)
    img.thumbnail((350,350))
    img = ImageTk.PhotoImage(img)
    lbl.configure(image=img)
    lbl.image = img
    img = np.array(img)

    cv2.imwrite(cv2.UMat("C:/Users/User/Desktop/Kurkuma/SEG" + ".jpg", img))

当我运行此代码时,我收到以下错误:TypeError: Expected Ptr<cv::UMat> for argument 'm'

我对 OpenCV 和 Tkinter 不太熟悉,所以我不知道如何解决这个问题。 谁能告诉我有什么问题或我必须改变什么?

您不应在np.array(img)中使用ImageTk.PhotoImage的结果。 使用Image的结果:

def select_image():
    fln = filedialog.askopenfilename(initialdir=os.getcwd(), title="Select image file", filetypes=(("JPG File","*.jpg"), ("PNG file", "*.png"), ("All Files", "*.*")))
    if fln:
        img = Image.open(fln)
        img.thumbnail((350,350))

        tkimg = ImageTk.PhotoImage(img) # use another variable
        lbl.configure(image=tkimg)
        lbl.image = tkimg

        img = np.array(img) # use result from Image.open()
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # convert RGB to BGR

        cv2.imwrite("C:/Users/User/Desktop/Kurkuma/SEG.jpg", img)

在转换为 NumPy 数组之前,您需要使用ImageTk.getimage(img)
在另存为 JPEG 之前,您还需要将颜色格式从 RGBA 转换为 BGR。

代码示例:

img = ImageTk.PhotoImage(img)  # Type of img is PIL.ImageTk.PhotoImage

# https://stackoverflow.com/questions/58389742/how-to-convert-imagetk-to-image
img = np.array(ImageTk.getimage(img))  # Get the image, and then convert it to NumPy array

img_bgr = cv2.cvtColor(img, cv2.COLOR_RGBA2BGR)  # Convent from RGBA to BGR color space

cv2.imwrite("img.jpg", img_bgr)  # Save to JPEG.

更有效的解决方案是不使用 OpenCV,也不使用ImageTk.PhotoImage

您可以简单地使用枕头使用img.save保存图像:

img.thumbnail((350,350))
img.save("img.jpg")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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