PIL对上传到Django的图片进行处理并保存

PIL对上传到Django的图片进行处理并保存

1. 介绍

上传的图片文件:如

pic = request.FILES["picture"]
# pic是 <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> 类型的数据

# 而pillow的Image.open("./xxx.jpg") 则是:

<class 'PIL.JpegImagePlugin.JpegImageFile'> 类型的数据

# 问题是如何把InMemoryUploadedFile转化为PIL类型,并且处理之后再转回InMemoryUploadedFile,并save

2. 把InMemoryUploadedFile转化为PIL类型

from PIL import Image

pic = request.FILES["picture"]
im_pic = Image.open(pic)
# 这样就把InMemoryUploadedFile转化为了PIL类型数据,pic是InMemoryUploadedFile,im_pic是PIL类型

3. 处理PIL类型的图片数据

w, h = im_pic.size
if w >= h:
    w_start = (w-h)*0.618
    box = (w_start, 0, w_start+h, h)
    region = im_pic.crop(box)
else:
    h_start = (h-w)*0.618
    box = (0, h_start, w, h_start+w)
    region = im_pic.crop(box)

# region就是PIL处理后的正方形了

4. 将处理后的PIL类型转化为InMemoryUploadedFile类型

from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile

// 先保存到磁盘io
pic_io = BytesIO()
region.save(pic_io, im_pic.format)
// 再转化为InMemoryUploadedFile数据
pic_file = InMemoryUploadedFile(
    file=pic_io,
    field_name=None,
    name=pic.name,
    content_type=pic.content_type,
    size=pic.size,
    charset=None
)

pic_file 就是region转化后的InMemoryUploadedFile了

5. 保存InMemoryUploadedFile到数据库

from ./models import Picture

p = Picture(picture=pic_file)
p.save()
好的,以下是一个基于Django图片分类预测应用示例,包含使用JavaScript显示上传的图片: 1. 创建Django项目并创建一个app,命名为`classifier` 2. 安装必要的Python包 ``` pip install tensorflow==2.6.0 tensorflow_hub==0.12.0 Pillow==8.3.1 django==3.2.7 ``` 3. 在`classifier` app中创建以下文件和文件夹: ``` classifier/ templates/ index.html models/ model.h5 static/ js/ main.js views.py ``` 4. 将训练好的模型文件保存到`models`文件夹中 5. 在`views.py`中添加以下代码: ```python from django.shortcuts import render from django.http import JsonResponse import tensorflow as tf import tensorflow_hub as hub from PIL import Image import numpy as np def index(request): return render(request, 'index.html') def predict(request): # 获取上传的图片文件 img_file = request.FILES['img'] # 打开图片并使用Pillow库进行处理 img = Image.open(img_file) img = img.resize((224, 224)) img_array = np.array(img) / 255.0 img_array = img_array.reshape(1, 224, 224, 3) # 加载模型并进行预测 model = tf.keras.models.load_model('classifier/models/model.h5', custom_objects={'KerasLayer': hub.KerasLayer}) predictions = model.predict(img_array) # 将预测结果转换为标签 labels = ['cat', 'dog'] prediction_label = labels[np.argmax(predictions)] # 返回JSON格式的预测结果 response_data = {'prediction': prediction_label} return JsonResponse(response_data) ``` 6. 在`templates`文件夹中创建`index.html`文件,并添加以下代码: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Image Classifier</title> </head> <body> <h1>Image Classifier</h1> <form method="post" enctype="multipart/form-data" id="upload-form"> {% csrf_token %} <input type="file" name="img" accept="image/*" onchange="previewImage(event)"> <img id="preview" src="" alt="Preview"> <input type="button" value="Predict" onclick="predict()"> </form> <div id="result"></div> <script src="{% static 'js/main.js' %}"></script> </body> </html> ``` 7. 在`static/js`文件夹中创建`main.js`文件,并添加以下代码: ```javascript function previewImage(event) { var preview = document.getElementById('preview'); preview.src = URL.createObjectURL(event.target.files[0]); preview.style.display = 'block'; } function predict() { var form_data = new FormData($('#upload-form')[0]); $.ajax({ type: 'POST', url: '/predict/', data: form_data, processData: false, contentType: false, success: function (data) { $('#result').text('Prediction: ' + data.prediction); }, error: function (error) { console.log(error); } }); } ``` 8. 运行Django应用程序并访问`http://localhost:8000/`,上传一张猫或狗的图片并预览,然后点击“预测”按钮,应用程序将返回预测结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值