首页 > 解决方案 > 如何使用 ImageTk.PhotoImage 从 ip 网络摄像头加载图像?

问题描述

我在 PIL.ImageTk.PhotoImage(img) 中尝试使用图像“img”时分享了我的代码,但它不起作用。

        while(True):
            imgResp=urllib.request.urlopen(self.ip)
            imgNp=np.array(bytearray(imgResp.read()),dtype=np.uint8)
            img=cv2.imdecode(imgNp,-1)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            bodies = body_classifier.detectMultiScale(img, 1.04, 3)
            for (x,y,w,h) in bodies:
                print("X", x)
                print("Y", y)
                print("W", w)
                print("H", h)
                cv2.imshow("CAMARA 1",img)
                self.canv = Canvas(self.window, bg='white')
                self.canv.grid(row=5, column=0)
                #self.imgLoad = PIL.ImageTk.PhotoImage(PIL.Image.open ("C:\\......jpg")) # works
                self.imgLoad = PIL.ImageTk.PhotoImage(img)                               # does not work
                self.canv.create_image(20,20, anchor=NW, image=self.imgLoad)

标签: python

解决方案


使用 numpy asarray 读取图像。

a = np.asarray(img)
img2 = Image.fromarray(a)
ImageTk.PhotoImage(img2)

推荐阅读