首页 > 解决方案 > AttributeError:“JpegImageFile”对象没有“读取”属性

问题描述

当我运行这些代码行时,出现此错误

AttributeError: 'JpegImageFile' 对象没有属性 'read'"

我似乎没有解决它。

import streamlit as st
import cv2
import os
import numpy as np
from PIL import Image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.models import load_model

def detect_mask(image):
    image = cv2.imdecode(np.fromstring(image.read(), dtype='uint8'),1)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    (h, w) = image.shape[:2]
    blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300), (104.0, 177.0, 123.0))
    net.setInput(blob)
    detection = net.forward()

标签: tensorflowopencv

解决方案


工作示例代码

import cv2
import os
import numpy as np
from PIL import Image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.models import load_model

image ='image.jpeg'
with open(image, 'rb') as infile:
     buf = infile.read()

x = np.fromstring(buf, dtype='uint8')
img = cv2.imdecode(x, 1)
imag = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
(h, w) = imag.shape[:2]
blob = cv2.dnn.blobFromImage(imag, 1.0, (300, 300), (104.0, 177.0, 123.0))

推荐阅读