如何使用 imread 读取图像?

时间:2021-04-02 11:08:48

标签: python-3.x tkinter

我正在尝试将 gui 添加到我基于 cnn 的深度学习项目中。 因此,在单击分类按钮时,我需要读取图像并将其发送到相同的预测函数以进行进一步处理。请在这里帮助我。我刚刚分享了部分代码。

def sample_prediction(test_im):
    feed_dict_test = {
        x: test_im.reshape(1, img_size_flat),
        y_true: np.array([[2,1,0]])
    }

    test_pred = session.run(y_pred_cls, feed_dict=feed_dict_test)
    return classes[test_pred[0]]

def classify(file_path):
    global label_packed
    image = Image.open(file_path)
    
    #image = image.resize((30,30))
    #image = numpy.expand_dims(image, axis=0)
    #image = numpy.array(image)
   
    #cv2.imshow("frame",inputface)
    #inputface = cv2.resize(inputface, (img_size, img_size), cv2.INTER_LINEAR) / 255

    pred =sample_prediction(image)
    sign = classes[pred+1]
    print(sign)

def show_classify_button(file_path):
    classify_b=Button(top,text="Classify X-ray Image",command=lambda: classify(file_path),padx=10,pady=5)
    classify_b.configure(background='#364156', foreground='white',font=('arial',10,'bold'))
    classify_b.place(relx=0.79,rely=0.46)
    
    label.configure(foreground='#011638', text=sign)

当我运行这个时,Tkinter 回调中的异常

Traceback (most recent call last):
  File "C:\Users\DELL\anaconda3\envs\Pneu Packages\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "cnn_train_test.py", line 489, in <lambda>
    classify_b=Button(top,text="Classify X-ray Image",command=lambda: classify(file_path),padx=10,pady=5)
  File "cnn_train_test.py", line 482, in classify
    pred =sample_prediction(image)
  File "cnn_train_test.py", line 372, in sample_prediction
    x: test_im.reshape(1, img_size_flat),
AttributeError: 'JpegImageFile' object has no attribute 'reshape'

1 个答案:

答案 0 :(得分:0)

您可以将图像作为 Numpy 数组或 PIL 图像读取、写入和处理,并且您可以随时在这两种类型之间移动。请注意,OpenCV 使用 BGR 排序,而 PIL 和大多数其他软件包采用 RGB。


因此,您可以使用 OpenCV 将图像读入 Numpy 数组:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Subject> query = cb.createQuery(Subject.class);
Root<Subject> root = query.from(Subject.class);
query
    .select(root)
    .where(cb.and(
        root.in(teacherSubjects).not(),
        cb.isFalse(root.get(Subject_.DELETED))
    ))

并使用 OpenCV 将该 Numpy 数组写入磁盘,使用:

import cv2

# Load a file into a Numpy array - "na" will be BGR order
na = cv2.imread('image.png', cv2.IMREAD_COLOR)

或者您可以使用 PIL 将图像加载为 PIL import cv2 # Write Numpy array to disk as image - "na" must be BGR order cv2.imwrite('result.jpg', na)

Image

并使用 PIL 将该 from PIL import Image # Load a file into a "PIL Image" pi = Image.open('input.jpg') 写入磁盘:

Image

您可以像这样将 PIL from PIL import Image # Save PIL Image to disk pi.save('result.png') 转换为 Numpy 数组:

Image

然后将 Numpy 数组转换为 PIL # Make Numpy array from PIL Image na = np.array(pi) ,如下所示:

Image

记住频道排序并可能使用它来重新排序频道:

# Make PIL Image from Numpy array
pi = Image.fromarray(na)

BGRarray = cv2.cvtColor(RGBarray, cv2.COLOR_RGB2BGR)
相关问题