File size: 2,511 Bytes
80914e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import gradio as gr
import torch
from PIL import Image
from ultralytics import YOLO
import matplotlib.pyplot as plt
import io
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
model = YOLO('detect-best.pt')

def predict(img, conf, iou):
    results = model.predict(img, conf=conf, iou=iou)
    name = results[0].names
    cls = results[0].boxes.cls
    crazing = 0
    inclusion = 0
    patches = 0
    pitted_surface = 0
    rolled_inscale = 0
    scratches = 0
    for i in cls:
        if i == 0:
            crazing += 1
        elif i == 1:
            inclusion += 1
        elif i == 2:
            patches += 1
        elif i == 3:
            pitted_surface += 1
        elif i == 4:
            rolled_inscale += 1
        elif i == 5:
            scratches += 1
        # 绘制柱状图
    fig, ax = plt.subplots()
    categories = ['crazing','inclusion', 'patches' ,'pitted_surface', 'rolled_inscale' ,'scratches']
    counts = [crazing,inclusion, patches ,pitted_surface, rolled_inscale ,scratches]
    ax.bar(categories, counts)
    ax.set_title('Category-Count')
    plt.ylim(0,5)
    plt.xticks(rotation=45, ha="right")
    ax.set_xlabel('Category')
    ax.set_ylabel('Count')
    # 将图表保存为字节流
    buf = io.BytesIO()
    canvas = FigureCanvas(fig)
    canvas.print_png(buf)
    plt.close(fig)  # 关闭图形,释放资源

    # 将字节流转换为PIL Image
    image_png = Image.open(buf)
    # 绘制并返回结果图片和类别计数图表

    for i, r in enumerate(results):
        # Plot results image
        im_bgr = r.plot()  # BGR-order numpy array
        im_rgb = Image.fromarray(im_bgr[..., ::-1])  # RGB-order PIL image

        # Show results to screen (in supported environments)
    return im_rgb, image_png


base_conf, base_iou = 0.25, 0.45
title = "基于改进YOLOv8算法的工业瑕疵辅助检测系统"
des = "鼠标点击上传图片即可检测缺陷,可通过鼠标调整预测置信度,还可点击网页最下方示例图片进行预测"
interface = gr.Interface(
    inputs=['image', gr.Slider(maximum=1, minimum=0, value=base_conf), gr.Slider(maximum=1, minimum=0, value=base_iou)],
    outputs=["image", 'image'], fn=predict, title=title, description=des,
    examples=[["example1.jpg", base_conf, base_iou],
              ["example2.jpg", base_conf, base_iou],
              ["example3.jpg", base_conf, base_iou]])
interface.launch()