{"id":29596,"date":"2025-04-20T11:06:11","date_gmt":"2025-04-20T03:06:11","guid":{"rendered":"https:\/\/www.wsisp.com\/helps\/29596.html"},"modified":"2025-04-20T11:06:11","modified_gmt":"2025-04-20T03:06:11","slug":"flask%e6%90%ad%e5%bb%ba%e5%be%ae%e6%9c%8d%e5%8a%a1%e5%99%a8%e5%b9%b6%e8%ae%ad%e7%bb%83cnn%e6%b0%b4%e6%9e%9c%e8%af%86%e5%88%ab%e6%a8%a1%e5%9e%8b%e5%ba%94%e7%94%a8%e4%ba%8e%e7%bd%91%e9%a1%b5","status":"publish","type":"post","link":"https:\/\/www.wsisp.com\/helps\/29596.html","title":{"rendered":"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875"},"content":{"rendered":"<h2>\u4e00. \u642d\u5efaflask\u73af\u5883<\/h2>\n<h4>\u6982\u5ff5<\/h4>\n<ul>\n<li>flask:\u4e00\u4e2a\u8f7b\u91cf\u7ea7\u00a0Web \u5e94\u7528\u6846\u67b6&#xff0c;\u88ab\u8bbe\u8ba1\u4e3a\u7b80\u5355\u3001\u7075\u6d3b&#xff0c;\u80fd\u591f\u5feb\u901f\u542f\u52a8\u4e00\u4e2a Web \u9879\u76ee\u3002<\/li>\n<li>CNN:\u6df1\u5ea6\u5b66\u4e60\u6a21\u578b&#xff0c;\u7528\u4e8e\u5904\u7406\u5177\u6709\u7f51\u683c\u72b6\u62d3\u6251\u7ed3\u6784\u7684\u6570\u636e&#xff0c;\u5982\u56fe\u50cf&#xff08;2D\u7f51\u683c&#xff09;\u548c\u89c6\u9891&#xff08;3D\u7f51\u683c&#xff09;\u3002<\/li>\n<li>PyTorch:\u5f00\u6e90\u7684\u673a\u5668\u5b66\u4e60\u5e93&#xff0c;\u5e94\u7528\u4e8e\u5982\u8ba1\u7b97\u673a\u89c6\u89c9\u548c\u81ea\u7136\u8bed\u8a00\u5904\u7406\u7b49\u9886\u57df\u7684\u6df1\u5ea6\u5b66\u4e60\u3002<\/li>\n<\/ul>\n<hr \/>\n<h4>flask\u73af\u5883\u642d\u5efa\u64cd\u4f5c\u6b65\u9aa4&#xff1a;\u00a0<\/h4>\n<\/p>\n<li>pycharm\u7ec8\u7aef\u521b\u5efa\u65b0\u7684\u865a\u62df\u73af\u5883&#xff1a;python -m venv virtualName \u3002<\/li>\n<li>\u6fc0\u6d3b\u865a\u62df\u73af\u5883\u3002<\/li>\n<li>\u5728\u865a\u62df\u73af\u5883\u4e2d\u5b89\u88c5flask\u3002<\/li>\n<li>\u8fd0\u884c\u7b2c\u4e00\u4e2a\u524d\u7aef\u7f51\u9875\u3002<\/li>\n<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:500px\">\n   \u6d41\u7a0b\u56fe\u4f8b <\/p>\n<tbody>\n<tr>\n<td>\n<h4>1.<\/h4>\n<p style=\"text-align:center\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"199\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030608-680464a019fa8.png\" width=\"500\" \/><\/p>\n<\/td>\n<td>\n<h4>2.<\/h4>\n<p style=\"text-align:center\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"165\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030608-680464a04c7dc.png\" width=\"500\" \/><\/p>\n<\/td>\n<\/tr>\n<tr>\n<td>\n<h4>3.<img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"213\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030608-680464a07ea35.png\" width=\"500\" \/><\/h4>\n<\/p>\n<\/td>\n<td>\n<h4>4.<img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"133\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030608-680464a0b98ad.png\" width=\"500\" \/><\/h4>\n<\/p>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h5>\u6b65\u9aa44\u4ee3\u7801&#xff1a;<\/h5>\n<p>from flask import Flask<br \/>\napp &#061; Flask(__name__)<\/p>\n<p>&#064;app.route(&#039;\/&#039;)<br \/>\ndef hello_world():<br \/>\n    return &#034;&lt;h1&gt;hello world!&lt;\/h1&gt;&#034;<\/p>\n<p>if __name__ &#061;&#061; &#039;__main__&#039;:<br \/>\n    app.run(debug&#061;True)<\/p>\n<hr \/>\n<h2>\u4e8c. \u8bad\u7ec3\u6c34\u679c\u6a21\u578b<\/h2>\n<h4>\u6c34\u679c\u8bc6\u522bCNN\u8bad\u7ec3\u64cd\u4f5c\u6b65\u9aa4&#xff1a;\u00a0<\/h4>\n<\/p>\n<li>\u51c6\u5907\u6570\u636e\u96c6(kaggle\u5b98\u7f51\u53ef\u4e0b\u8f7d)\u3002<\/li>\n<li>\u5b89\u88c5pyrorch\u3002<\/li>\n<li>\u4f7f\u7528pytorch\u7684nn\u6a21\u578b\u5b9a\u4e49\u53c2\u6570\u3002<\/li>\n<li>\u8bad\u7ec3\u6a21\u578b\u3002<\/li>\n<li>\u5f97\u5230\u8bad\u7ec3\u597d\u7684pth\u6a21\u578b\u3002<\/li>\n<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:500px\">\n   \u6d41\u7a0b\u56fe\u4f8b <\/p>\n<tbody>\n<tr>\n<td>\n<h4>1.<\/h4>\n<p style=\"text-align:center\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"326\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030609-680464a10de1d.png\" width=\"500\" \/><\/p>\n<\/td>\n<td>\n<h4>2.<\/h4>\n<p style=\"text-align:center\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"90\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030609-680464a1ac8bf.png\" width=\"500\" \/><\/p>\n<\/td>\n<\/tr>\n<tr>\n<td colspan=\"2\">\n<h4>5.<img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"117\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030609-680464a1e10f3.png\" width=\"500\" \/><\/h4>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<h5>\u6b65\u9aa43\u4ee3\u7801&#xff1a;<\/h5>\n<p>import torch<br \/>\nfrom torch import nn<\/p>\n<p># \u6c34\u679c\u5206\u7c7b\u6a21\u578b\u53c2\u6570\u914d\u7f6e<\/p>\n<p>class NumberNet(nn.Module):<br \/>\n    def __init__(self, device, classes&#061;10):<br \/>\n        super().__init__()<br \/>\n        if device is None:<br \/>\n            device &#061; torch.device(&#034;cpu&#034;)<br \/>\n            if torch.cuda.is_available():<br \/>\n                device &#061; torch.device(&#034;cuda:0&#034;)<br \/>\n        self.cnn &#061; nn.Sequential(<br \/>\n            nn.Conv2d(3, 16, 3),  # 100&#215;100 -&gt; 98&#215;98<br \/>\n            nn.ReLU(),<br \/>\n            nn.MaxPool2d(2, 2),  # 98&#215;98 -&gt; 49&#215;49<br \/>\n            nn.Conv2d(16, 32, 3, padding&#061;1),  # 49&#215;49 -&gt; 49&#215;49<br \/>\n            nn.ReLU(),<br \/>\n            nn.MaxPool2d(2, 2),  # 49&#215;49 -&gt; 24&#215;24<br \/>\n            nn.Conv2d(32, 64, 3, padding&#061;1),  # 24&#215;24 -&gt; 24&#215;24<br \/>\n            nn.ReLU(),<br \/>\n            nn.MaxPool2d(2, 2),  # 24&#215;24 -&gt; 12&#215;12<br \/>\n            nn.Flatten(),<br \/>\n            nn.Dropout(),<br \/>\n            nn.Linear(64 * 12 * 12, 1024),  # \u8c03\u6574\u7ebf\u6027\u5c42\u7684\u8f93\u5165\u7279\u5f81\u6570\u91cf<br \/>\n            nn.ReLU(),<br \/>\n            nn.Dropout(),<br \/>\n            nn.Linear(1024, classes),<br \/>\n            nn.LogSoftmax(dim&#061;-1)<br \/>\n        )<\/p>\n<p>    def forward(self, X):<br \/>\n        return self.cnn(X)<\/p>\n<h5>\u6b65\u9aa44\u4ee3\u7801&#xff1a;<\/h5>\n<p>import torch<br \/>\nfrom torch import nn<br \/>\nfrom NumberNet import NumberNet<br \/>\nfrom torchvision import transforms<br \/>\nfrom torchvision.datasets import ImageFolder<br \/>\nfrom torch.utils.data import random_split<\/p>\n<p># \u6c34\u679c\u5206\u7c7b\u8bad\u7ec3<br \/>\n# \u6570\u636e\u96c6\u914d\u7f6e<br \/>\n# \u5047\u8bbe NumberNet \u6a21\u578b\u671f\u671b\u7684\u8f93\u5165\u662f 3 \u901a\u9053\u5f69\u8272\u56fe\u50cf<br \/>\ntransform &#061; transforms.Compose([<br \/>\n    transforms.ToTensor(),  # \u8fd9\u5c06\u628a PIL \u56fe\u50cf\u6216 NumPy \u6570\u7ec4\u8f6c\u6362\u4e3a\u5f20\u91cf&#xff0c;\u5e76\u4e14\u8303\u56f4\u4ece [0, 255] \u6807\u51c6\u5316\u5230 [0.0, 1.0]<br \/>\n    # transforms.Normalize(mean&#061;[0.485, 0.456, 0.406], std&#061;[0.229, 0.224, 0.225])  # \u53ef\u9009&#xff1a;\u6807\u51c6\u5316<br \/>\n])<\/p>\n<p># \u52a0\u8f7d\u9879\u76ee\u76ee\u5f55\u4e0b\u7684\u6c34\u679c\u6587\u4ef6\u5939<br \/>\nimg_dataset &#061; ImageFolder(&#034;..\/fruits&#034;, transform&#061;transform)<br \/>\nlen_dataset &#061; len(img_dataset)<br \/>\ntrain_size &#061; int(len_dataset * 0.8)<br \/>\nvalid_size &#061; len_dataset &#8211; train_size<br \/>\ntrain_dataset, valid_dataset &#061; random_split(img_dataset, [train_size, valid_size])<\/p>\n<p># \u6570\u636e\u52a0\u8f7d\u5668<br \/>\ntrain_dataloader &#061; torch.utils.data.DataLoader(train_dataset, batch_size&#061;1000, shuffle&#061;True)<br \/>\nvalid_dataloader &#061; torch.utils.data.DataLoader(valid_dataset, batch_size&#061;1000)<br \/>\n# batch_total \u5e94\u8be5\u662f dataloader \u7684\u603b\u6279\u6b21\u6570\u91cf&#xff0c;\u8fd9\u91cc\u8ba1\u7b97\u65b9\u5f0f\u4e0d\u6b63\u786e<br \/>\nbatch_total &#061; len(train_dataloader)  # \u5e94\u8be5\u76f4\u63a5\u4f7f\u7528 len(dataloader)<\/p>\n<p># \u4f7f\u7528conda\u6216\u8005cpu\u5f00\u59cb\u8bad\u7ec3<br \/>\ndevice &#061; torch.device(&#034;cuda:0&#034; if torch.cuda.is_available() else &#034;cpu&#034;)<br \/>\nepochs &#061; 10<br \/>\nmodel &#061; NumberNet(device)<br \/>\ncriterion &#061; nn.CrossEntropyLoss()<br \/>\nadam &#061; torch.optim.Adam(model.parameters(), lr&#061;0.01)<\/p>\n<p>for epoch in range(epochs):<br \/>\n    losses &#061; []<br \/>\n    for batch_num, (images, labels) in enumerate(train_dataloader, start&#061;1):  # \u4f7f\u7528 enumerate \u6765\u83b7\u53d6\u6279\u6b21\u7f16\u53f7<br \/>\n        adam.zero_grad()<br \/>\n        predict &#061; model(images.to(device))<br \/>\n        loss &#061; criterion(predict, labels.to(device))<br \/>\n        print(f&#034;batch size: {batch_num} \/ {batch_total} &#8212; loss: {loss.item():.4f} &#034;)<br \/>\n        losses.append(loss.item())<br \/>\n        loss.backward()<br \/>\n        adam.step()<br \/>\n    acc_list &#061; []<br \/>\n    with torch.no_grad():<br \/>\n        for images, labels in valid_dataloader:<br \/>\n            predict &#061; model(images.to(device))<br \/>\n            result &#061; torch.argmax(predict, dim&#061;-1)<br \/>\n            acc &#061; (result &#061;&#061; labels.to(device)).float().mean()  # \u4f7f\u7528 torch \u7684\u51fd\u6570\u6765\u8ba1\u7b97\u51c6\u786e\u7387<br \/>\n            acc_list.append(acc.item())<\/p>\n<p>    total_acc &#061; sum(acc_list) \/ len(acc_list)<br \/>\n    total_loss &#061; sum(losses) \/ batch_total<br \/>\n    print(f&#034;epoch: {epoch &#043; 1} \/ {epochs} &#8212; loss: {total_loss:.4f} &#8212; acc: {total_acc:.4f} &#034;)<\/p>\n<p># \u4fdd\u5b58\u6a21\u578b\u53c2\u6570&#xff0c;\u800c\u4e0d\u662f\u6574\u4e2a\u6a21\u578b<br \/>\ntorch.save(model, &#034;..\/readyModel\/model.pth&#034;)<\/p>\n<hr \/>\n<h2>\u00a0\u4e09. \u5c06\u8bad\u7ec3\u597d\u7684\u6a21\u578b\u5d4c\u5165flask\u540e\u7aef<\/h2>\n<h4>\u5b9e\u73b0\u6c34\u679c\u8bc6\u522bweb\u64cd\u4f5c\u6b65\u9aa4&#xff1a;\u00a0<\/h4>\n<\/p>\n<li>\u5728\u865a\u62df\u5316\u73af\u5883\u4e0b\u521b\u5efa.py\u540e\u7aef\u542f\u52a8\u6587\u4ef6&#xff0c;\u5e76\u4e14\u521b\u5efa\u6a21\u578b\u5b9e\u4f8b&#xff0c;\u540c\u65f6\u5c06\u8bad\u7ec3\u597d\u7684.pth\u6587\u4ef6\u653e\u5165\u4ee3\u7801\u5bf9\u5e94\u7684\u6587\u4ef6\u8def\u5f84\u3002<\/li>\n<li>\u521b\u5efaindex.html\u6587\u4ef6&#xff0c;\u4f5c\u4e3a\u540e\u7eed\u524d\u7aef\u6587\u4ef6\u3002<\/li>\n<li>\u5728\u524d\u7aef\u4ee3\u7801\u548c\u540e\u7aef\u4ee3\u7801\u4f7f\u7528Jason\u8fdb\u884c\u8def\u7531\u3002<\/li>\n<li>\u542f\u52a8\u9879\u76ee&#xff0c;\u5b9e\u73b0\u529f\u80fd\u3002<\/li>\n<h5>\u00a0\u6b65\u9aa41\u4ee3\u7801&#xff1a;<\/h5>\n<p>from flask import Flask, render_template, request, jsonify<br \/>\nimport time<br \/>\nimport torch<br \/>\nimport cv2<br \/>\nimport numpy as np<br \/>\nfrom FruitNet import FruitNet  # \u786e\u4fddFruitNet\u5b9a\u4e49\u662f\u6b63\u786e\u7684<\/p>\n<p>app &#061; Flask(__name__)<\/p>\n<p># \u5b9a\u4e49\u8bbe\u5907<br \/>\ndevice &#061; torch.device(&#034;cuda&#034; if torch.cuda.is_available() else &#034;cpu&#034;)<\/p>\n<p># \u521b\u5efa\u6a21\u578b\u5b9e\u4f8b<br \/>\nmodel &#061; FruitNet(device&#061;device, classes&#061;5)  # \u786e\u4fdd\u7c7b\u522b\u6570\u4e0e\u8bad\u7ec3\u65f6\u4e00\u81f4<br \/>\nmodel.to(device)<\/p>\n<p># \u52a0\u8f7d\u8bad\u7ec3\u597d\u7684\u6743\u91cd<br \/>\nmodel.load_state_dict(torch.load(&#034;static\/fruit_model.pth&#034;))  # \u786e\u4fdd\u6743\u91cd\u6587\u4ef6\u540d\u4e3afruit_model.pth<br \/>\nmodel.eval()  # \u8bbe\u7f6e\u6a21\u578b\u4e3a\u8bc4\u4f30\u6a21\u5f0f<\/p>\n<p>def predict_image(image_data):<br \/>\n    # \u901a\u8fc7cv2\u52a0\u8f7d\u56fe\u7247\u6570\u636e<br \/>\n    img &#061; cv2.imdecode(np.frombuffer(image_data, np.uint8), cv2.IMREAD_COLOR)<\/p>\n<p>    # \u5c06\u56fe\u50cf\u4eceBGR\u8f6c\u6362\u4e3aRGB\u683c\u5f0f&#xff08;\u56e0\u4e3aOpenCV\u9ed8\u8ba4\u52a0\u8f7d\u7684\u662fBGR\u683c\u5f0f&#xff09;<br \/>\n    img &#061; cv2.cvtColor(img, cv2.COLOR_BGR2RGB)<\/p>\n<p>    # \u8c03\u6574\u56fe\u7247\u5927\u5c0f\u5230100&#215;100&#xff08;\u4e0e\u8bad\u7ec3\u65f6\u7684\u8f93\u5165\u5927\u5c0f\u4e00\u81f4&#xff09;<br \/>\n    img &#061; cv2.resize(img, (100, 100))<\/p>\n<p>    # \u5728\u7b2c\u4e00\u4e2a\u4f4d\u7f6e\u589e\u52a0\u4e00\u4e2a\u7ef4\u5ea6&#xff0c;\u5f62\u6210batch\u5927\u5c0f\u4e3a1<br \/>\n    img &#061; np.expand_dims(img, 0)<\/p>\n<p>    # \u5c06numpy\u5bf9\u8c61\u8f6c\u5316\u4e3apytorch\u7684tensor\u5bf9\u8c61<br \/>\n    img &#061; torch.from_numpy(img)<\/p>\n<p>    # \u8c03\u6574\u56fe\u50cf\u901a\u9053\u987a\u5e8f<br \/>\n    img &#061; torch.permute(img, [0, 3, 1, 2])  # \u8f6c\u6362\u4e3a (batch_size, channels, height, width)<\/p>\n<p>    # \u6d4b\u8bd5\u6700\u7ec8\u7684\u7ed3\u679c<br \/>\n    with torch.no_grad():  # \u5173\u95ed\u68af\u5ea6\u8ba1\u7b97<br \/>\n        img &#061; img.to(device).float()  # \u786e\u4fdd\u8f93\u5165\u662ffloat\u7c7b\u578b&#xff0c;\u5e76\u53d1\u9001\u5230\u6307\u5b9a\u8bbe\u5907<br \/>\n        predict &#061; model(img)<br \/>\n        predicted_class &#061; torch.argmax(predict, dim&#061;-1).item()<\/p>\n<p>    # \u5b9a\u4e49\u6c34\u679c\u7c7b\u522b\u6807\u7b7e<br \/>\n    fruit_classes &#061; [&#034;Apple Golden 1&#034;, &#034;Banana&#034;, &#034;Pear Red&#034;, &#034;Tomato Heart&#034;, &#034;Watermelon&#034;]  # \u6839\u636e\u4f60\u7684\u6570\u636e\u96c6\u5b9a\u4e49\u7c7b\u522b\u6807\u7b7e<\/p>\n<p>    # \u8f93\u51fa\u9884\u6d4b\u7684\u6c34\u679c\u79cd\u7c7b<br \/>\n    predicted_fruit &#061; fruit_classes[predicted_class]<br \/>\n    return predicted_fruit <\/p>\n<h5>\u00a0\u6b65\u9aa42\u4ee3\u7801&#xff1a;<\/h5>\n<p>&lt;!DOCTYPE html&gt;<br \/>\n&lt;html lang&#061;&#034;en&#034;&gt;<br \/>\n&lt;head&gt;<br \/>\n    &lt;meta charset&#061;&#034;UTF-8&#034;&gt;<br \/>\n    &lt;title&gt;\u6c34\u679c\u8bc6\u522b&lt;\/title&gt;<br \/>\n    &lt;link rel&#061;&#034;stylesheet&#034; href&#061;&#034;.\/static\/css\/index.css&#034;&gt;<br \/>\n    &lt;script src&#061;&#034;.\/static\/js\/jquery-3.7.1.min.js&#034;&gt;&lt;\/script&gt;<br \/>\n&lt;\/head&gt;<br \/>\n&lt;body&gt;<br \/>\n&lt;div class&#061;&#034;main&#034;&gt;<br \/>\n    &lt;div&gt;<br \/>\n        &lt;!&#8211; \u663e\u793a\u4e0a\u4f20\u7684\u56fe\u7247 &#8211;&gt;<br \/>\n        &lt;div class&#061;&#034;upload-img&#034;&gt;<br \/>\n            &lt;img id&#061;&#034;upload-img&#034; src&#061;&#034;&#034; alt&#061;&#034;\u8bf7\u4e0a\u4f20\u56fe\u7247&#034;\/&gt;<br \/>\n        &lt;\/div&gt;<\/p>\n<p>        &lt;!&#8211; \u8868\u5355\u7528\u4e8e\u4e0a\u4f20\u56fe\u7247 &#8211;&gt;<br \/>\n        &lt;form   id&#061;&#034;upload-btn&#034; action&#061;&#034;\/upload&#034; method&#061;&#034;post&#034; enctype&#061;&#034;multipart\/form-data&#034;&gt;<br \/>\n            &lt;input style&#061;&#034;margin-left: 120px&#034; type&#061;&#034;file&#034; name&#061;&#034;the_file&#034; id&#061;&#034;selectImg&#034;&gt; &lt;br\/&gt;<br \/>\n            &lt;input type&#061;&#034;submit&#034; value&#061;&#034;\u8bc6\u522b\u8be5\u6c34\u679c&#034;&gt;<br \/>\n        &lt;\/form&gt;<br \/>\n    &lt;\/div&gt;<\/p>\n<p>    &lt;!&#8211; \u663e\u793a\u8bc6\u522b\u7ed3\u679c &#8211;&gt;<br \/>\n    &lt;div class&#061;&#034;result&#034;&gt;<br \/>\n        &lt;h2 id&#061;&#034;result-show&#034;&gt;&lt;\/h2&gt;<br \/>\n    &lt;\/div&gt;<br \/>\n&lt;\/div&gt;<\/p>\n<p>&lt;script&gt;<br \/>\n    \/\/ \u5c06\u6587\u4ef6\u8f6c\u4e3a Base64 \u7528\u4e8e\u56fe\u7247\u9884\u89c8<br \/>\n    function convertToBase64(file, callback) {<br \/>\n        const reader &#061; new FileReader();<br \/>\n        reader.onload &#061; function(e) {<br \/>\n            callback(e.target.result);<br \/>\n        };<br \/>\n        reader.readAsDataURL(file);<br \/>\n    }<\/p>\n<p>    $(function(){<br \/>\n        \/\/ \u5904\u7406\u56fe\u7247\u9009\u62e9\u540e\u7684\u663e\u793a<br \/>\n        $(&#034;#selectImg&#034;).change(function(ev){<br \/>\n            const file &#061; $(this)[0].files[0];<br \/>\n            if (file) {<br \/>\n                convertToBase64(file, function(base64Img){<br \/>\n                    $(&#034;#upload-img&#034;).attr(&#034;src&#034;, base64Img);  \/\/ \u66f4\u65b0\u56fe\u7247\u9884\u89c8<br \/>\n                });<br \/>\n            }<br \/>\n        });<\/p>\n<p>        \/\/ \u5904\u7406\u8868\u5355\u63d0\u4ea4<br \/>\n        $(&#039;#upload-btn&#039;).submit(function(ev){<br \/>\n            ev.preventDefault();  \/\/ \u963b\u6b62\u9ed8\u8ba4\u8868\u5355\u63d0\u4ea4<\/p>\n<p>            var formData &#061; new FormData(this);  \/\/ \u83b7\u53d6\u8868\u5355\u6570\u636e<br \/>\n            $.ajax({<br \/>\n                url: &#039;\/upload&#039;,  \/\/ \u8bf7\u6c42\u7684\u540e\u7aef\u5730\u5740<br \/>\n                type: &#039;POST&#039;,<br \/>\n                data: formData,<br \/>\n                contentType: false,<br \/>\n                processData: false,<br \/>\n                success: function(response){<br \/>\n                    console.log(&#039;\u6587\u4ef6\u4e0a\u4f20\u6210\u529f&#039;);<br \/>\n                    console.log(response);<\/p>\n<p>                    \/\/ \u66f4\u65b0\u8bc6\u522b\u7ed3\u679c<br \/>\n                    $(&#039;#result-show&#039;).text(&#039;\u8bc6\u522b\u7ed3\u679c&#xff1a;&#039; &#043; response.result);  \/\/ \u663e\u793a\u8bc6\u522b\u7ed3\u679c<br \/>\n                },<br \/>\n                error: function(error){<br \/>\n                    console.error(&#039;\u6587\u4ef6\u4e0a\u4f20\u5931\u8d25&#039;);<br \/>\n                    console.error(error);<br \/>\n                }<br \/>\n            });<br \/>\n        });<br \/>\n    });<br \/>\n&lt;\/script&gt;<br \/>\n&lt;\/body&gt;<br \/>\n&lt;\/html&gt;<\/p>\n<h5>\u00a0\u6b65\u9aa43\u4ee3\u7801&#xff1a;<\/h5>\n<p>&lt;script&gt;<br \/>\n    \/\/ \u5c06\u6587\u4ef6\u8f6c\u4e3a Base64 \u7528\u4e8e\u56fe\u7247\u9884\u89c8<br \/>\n    function convertToBase64(file, callback) {<br \/>\n        const reader &#061; new FileReader();<br \/>\n        reader.onload &#061; function(e) {<br \/>\n            callback(e.target.result);<br \/>\n        };<br \/>\n        reader.readAsDataURL(file);<br \/>\n    }<\/p>\n<p>    $(function(){<br \/>\n        \/\/ \u5904\u7406\u56fe\u7247\u9009\u62e9\u540e\u7684\u663e\u793a<br \/>\n        $(&#034;#selectImg&#034;).change(function(ev){<br \/>\n            const file &#061; $(this)[0].files[0];<br \/>\n            if (file) {<br \/>\n                convertToBase64(file, function(base64Img){<br \/>\n                    $(&#034;#upload-img&#034;).attr(&#034;src&#034;, base64Img);  \/\/ \u66f4\u65b0\u56fe\u7247\u9884\u89c8<br \/>\n                });<br \/>\n            }<br \/>\n        });<\/p>\n<p>        \/\/ \u5904\u7406\u8868\u5355\u63d0\u4ea4<br \/>\n        $(&#039;#upload-btn&#039;).submit(function(ev){<br \/>\n            ev.preventDefault();  \/\/ \u963b\u6b62\u9ed8\u8ba4\u8868\u5355\u63d0\u4ea4<\/p>\n<p>            var formData &#061; new FormData(this);  \/\/ \u83b7\u53d6\u8868\u5355\u6570\u636e<br \/>\n            $.ajax({<br \/>\n                url: &#039;\/upload&#039;,  \/\/ \u8bf7\u6c42\u7684\u540e\u7aef\u5730\u5740<br \/>\n                type: &#039;POST&#039;,<br \/>\n                data: formData,<br \/>\n                contentType: false,<br \/>\n                processData: false,<br \/>\n                success: function(response){<br \/>\n                    console.log(&#039;\u6587\u4ef6\u4e0a\u4f20\u6210\u529f&#039;);<br \/>\n                    console.log(response);<\/p>\n<p>                    \/\/ \u66f4\u65b0\u8bc6\u522b\u7ed3\u679c<br \/>\n                    $(&#039;#result-show&#039;).text(&#039;\u8bc6\u522b\u7ed3\u679c&#xff1a;&#039; &#043; response.result);  \/\/ \u663e\u793a\u8bc6\u522b\u7ed3\u679c<br \/>\n                },<br \/>\n                error: function(error){<br \/>\n                    console.error(&#039;\u6587\u4ef6\u4e0a\u4f20\u5931\u8d25&#039;);<br \/>\n                    console.error(error);<br \/>\n                }<br \/>\n            });<br \/>\n        });<br \/>\n    });<br \/>\n&lt;\/script&gt;<br \/>\n&#064;app.route(&#034;\/&#034;)<br \/>\ndef home():<br \/>\n    return render_template(&#034;index.html&#034;)<\/p>\n<p>&#064;app.route(&#039;\/upload&#039;, methods&#061;[&#039;POST&#039;])<br \/>\ndef upload_file():<br \/>\n    if request.method &#061;&#061; &#039;POST&#039;:<br \/>\n        f &#061; request.files[&#039;the_file&#039;]<br \/>\n        # \u4fdd\u5b58\u56fe\u7247\u5230\u9759\u6001\u76ee\u5f55<br \/>\n        timestamp &#061; time.strftime(&#034;%Y%m%d%H%M%S&#034;)<br \/>\n        file_path &#061; f&#039;.\/static\/uploads\/{timestamp}.png&#039;<br \/>\n        f.save(file_path)<\/p>\n<p>        # \u8bfb\u53d6\u4fdd\u5b58\u540e\u7684\u56fe\u7247\u6570\u636e\u5e76\u9884\u6d4b<br \/>\n        with open(file_path, &#039;rb&#039;) as image_file:<br \/>\n            image_data &#061; image_file.read()<\/p>\n<p>        predicted_fruit &#061; predict_image(image_data)<\/p>\n<p>        # \u8fd4\u56deJSON\u6570\u636e<br \/>\n        return jsonify({<br \/>\n            &#039;file_id&#039;: timestamp,<br \/>\n            &#039;result&#039;: predicted_fruit,<br \/>\n            &#039;img_path&#039;: f&#039;\/static\/uploads\/{timestamp}.png&#039;<br \/>\n        }) <\/p>\n<h5>\u00a0 \u6b65\u9aa44\u5b9e\u73b0\u6548\u679c&#xff1a;<\/h5>\n<p class=\"img-center\"><img loading=\"lazy\" decoding=\"async\" alt=\"\" height=\"666\" src=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030610-680464a20f826.png\" width=\"1154\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb958\u6b21\uff0c\u70b9\u8d5e9\u6b21\uff0c\u6536\u85cf8\u6b21\u3002\u3010\u4ee3\u7801\u3011flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875\u3002_flask cnn<\/p>\n","protected":false},"author":2,"featured_media":29588,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[587,2394,153,81,2395,2393],"topic":[],"class_list":["post-29596","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-server","tag-587","tag-cnn","tag-flask","tag-python","tag-2395","tag-2393"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.3 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.wsisp.com\/helps\/29596.html\" \/>\n<meta property=\"og:locale\" content=\"zh_CN\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"og:description\" content=\"\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb958\u6b21\uff0c\u70b9\u8d5e9\u6b21\uff0c\u6536\u85cf8\u6b21\u3002\u3010\u4ee3\u7801\u3011flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875\u3002_flask cnn\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.wsisp.com\/helps\/29596.html\" \/>\n<meta property=\"og:site_name\" content=\"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\" \/>\n<meta property=\"article:published_time\" content=\"2025-04-20T03:06:11+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030608-680464a019fa8.png\" \/>\n<meta name=\"author\" content=\"admin\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"\u4f5c\u8005\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin\" \/>\n\t<meta name=\"twitter:label2\" content=\"\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 \u5206\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/29596.html\",\"url\":\"https:\/\/www.wsisp.com\/helps\/29596.html\",\"name\":\"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"isPartOf\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\"},\"datePublished\":\"2025-04-20T03:06:11+00:00\",\"dateModified\":\"2025-04-20T03:06:11+00:00\",\"author\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\"},\"breadcrumb\":{\"@id\":\"https:\/\/www.wsisp.com\/helps\/29596.html#breadcrumb\"},\"inLanguage\":\"zh-Hans\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.wsisp.com\/helps\/29596.html\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/29596.html#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\u9996\u9875\",\"item\":\"https:\/\/www.wsisp.com\/helps\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#website\",\"url\":\"https:\/\/www.wsisp.com\/helps\/\",\"name\":\"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3\",\"description\":\"\u9999\u6e2f\u670d\u52a1\u5668_\u9999\u6e2f\u4e91\u670d\u52a1\u5668\u8d44\u8baf_\u670d\u52a1\u5668\u5e2e\u52a9\u6587\u6863_\u670d\u52a1\u5668\u6559\u7a0b\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.wsisp.com\/helps\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"zh-Hans\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41\",\"name\":\"admin\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"zh-Hans\",\"@id\":\"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery\",\"contentUrl\":\"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery\",\"caption\":\"admin\"},\"sameAs\":[\"http:\/\/wp.wsisp.com\"],\"url\":\"https:\/\/www.wsisp.com\/helps\/author\/admin\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.wsisp.com\/helps\/29596.html","og_locale":"zh_CN","og_type":"article","og_title":"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","og_description":"\u6587\u7ae0\u6d4f\u89c8\u9605\u8bfb958\u6b21\uff0c\u70b9\u8d5e9\u6b21\uff0c\u6536\u85cf8\u6b21\u3002\u3010\u4ee3\u7801\u3011flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875\u3002_flask cnn","og_url":"https:\/\/www.wsisp.com\/helps\/29596.html","og_site_name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","article_published_time":"2025-04-20T03:06:11+00:00","og_image":[{"url":"https:\/\/www.wsisp.com\/helps\/wp-content\/uploads\/2025\/04\/20250420030608-680464a019fa8.png"}],"author":"admin","twitter_card":"summary_large_image","twitter_misc":{"\u4f5c\u8005":"admin","\u9884\u8ba1\u9605\u8bfb\u65f6\u95f4":"5 \u5206"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.wsisp.com\/helps\/29596.html","url":"https:\/\/www.wsisp.com\/helps\/29596.html","name":"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875 - \u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","isPartOf":{"@id":"https:\/\/www.wsisp.com\/helps\/#website"},"datePublished":"2025-04-20T03:06:11+00:00","dateModified":"2025-04-20T03:06:11+00:00","author":{"@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41"},"breadcrumb":{"@id":"https:\/\/www.wsisp.com\/helps\/29596.html#breadcrumb"},"inLanguage":"zh-Hans","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.wsisp.com\/helps\/29596.html"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.wsisp.com\/helps\/29596.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\u9996\u9875","item":"https:\/\/www.wsisp.com\/helps"},{"@type":"ListItem","position":2,"name":"flask\u642d\u5efa\u5fae\u670d\u52a1\u5668\u5e76\u8bad\u7ec3CNN\u6c34\u679c\u8bc6\u522b\u6a21\u578b\u5e94\u7528\u4e8e\u7f51\u9875"}]},{"@type":"WebSite","@id":"https:\/\/www.wsisp.com\/helps\/#website","url":"https:\/\/www.wsisp.com\/helps\/","name":"\u7f51\u7855\u4e92\u8054\u5e2e\u52a9\u4e2d\u5fc3","description":"\u9999\u6e2f\u670d\u52a1\u5668_\u9999\u6e2f\u4e91\u670d\u52a1\u5668\u8d44\u8baf_\u670d\u52a1\u5668\u5e2e\u52a9\u6587\u6863_\u670d\u52a1\u5668\u6559\u7a0b","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.wsisp.com\/helps\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"zh-Hans"},{"@type":"Person","@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/358e386c577a3ab51c4493330a20ad41","name":"admin","image":{"@type":"ImageObject","inLanguage":"zh-Hans","@id":"https:\/\/www.wsisp.com\/helps\/#\/schema\/person\/image\/","url":"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery","contentUrl":"https:\/\/gravatar.wp-china-yes.net\/avatar\/?s=96&d=mystery","caption":"admin"},"sameAs":["http:\/\/wp.wsisp.com"],"url":"https:\/\/www.wsisp.com\/helps\/author\/admin"}]}},"_links":{"self":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/29596","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/comments?post=29596"}],"version-history":[{"count":0,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/posts\/29596\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/media\/29588"}],"wp:attachment":[{"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/media?parent=29596"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/categories?post=29596"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/tags?post=29596"},{"taxonomy":"topic","embeddable":true,"href":"https:\/\/www.wsisp.com\/helps\/wp-json\/wp\/v2\/topic?post=29596"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}