开启辅助访问 切换到宽版

精易论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

用微信号发送消息登录论坛

新人指南 邀请好友注册 - 我关注人的新帖 教你赚取精币 - 每日签到


求职/招聘- 论坛接单- 开发者大厅

论坛版规 总版规 - 建议/投诉 - 应聘版主 - 精华帖总集 积分说明 - 禁言标准 - 有奖举报

查看: 389|回复: 9
收起左侧

[其它源码] txtp yolo点选模型py

[复制链接]
结帖率:71% (5/7)
发表于 3 天前 | 显示全部楼层 |阅读模式   重庆市重庆市
分享源码
界面截图: -
是否带模块: -
备注说明: -
from ultralytics import YOLO
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont

# 加载模型(如报错请先安装ultralytics: pip install ultralytics)
model = YOLO('best.pt')  # 用Ultralytics的YOLO类加载

# 输入图片文件夹
img_dir = Path('images')  # 你的图片目录,注意路径前加r或用双斜杠
img_files = list(img_dir.glob('*.jpg')) + list(img_dir.glob('*.png')) + list(img_dir.glob('*.bmp'))

# 输出结果文件夹(图片)
output_img_dir = Path('output_img')
output_img_dir.mkdir(exist_ok=True)

for img_path in img_files:
    results = model(img_path)
    for r in results:
        if hasattr(r, 'boxes') and r.boxes is not None and len(r.boxes) > 0:
            # 提取所有目标的中心点坐标、框、分类名
            all_targets = []  # [(cx, cy, idx, [x1, y1, x2, y2], class_id)]
            for idx, box in enumerate(r.boxes):
                x1, y1, x2, y2 = box.xyxy[0].tolist()
                cx = (x1 + x2) / 2
                cy = (y1 + y2) / 2
                class_id = int(box.cls[0].item()) if hasattr(box, 'cls') else -1
                all_targets.append((cx, cy, idx, [x1, y1, x2, y2], class_id))
            # 取y最大的3个(最下面的3个),按x从小到大排序
            bottom3 = sorted(all_targets, key=lambda x: -x[1])[:3
            bottom3 = sorted(bottom3, key=lambda x: x[0])
            # 对每个bottom3,找上方且分类id相同且x最接近的目标
            matched_top = []
            used_top_idx = set()
            for b in bottom3:
                bx, by, bidx, bbox, bcls = b
                # 在所有上方且分类id相同且未被匹配过的目标中找x最接近的
                candidates = [t for t in all_targets if t[1 < by and t[4 == bcls and t[2 not in used_top_idx
                if not candidates:
                    continue
                best_top = min(candidates, key=lambda t: abs(t[0 - bx))
                matched_top.append(best_top)
                used_top_idx.add(best_top[2])
            # 画框和数字
            img_with_boxes = r.plot()
            img_pil = Image.fromarray(img_with_boxes)
            draw = ImageDraw.Draw(img_pil)
            try:
                font = ImageFont.truetype("arial.ttf", 32)
            except:
                font = None
            for i, (cx, cy, idx, (x1, y1, x2, y2), class_id) in enumerate(matched_top):
                label = f"{i+1}"
                draw.text((x1, y1-30), label, fill=(0,0,255), font=font)
            output_img_path = output_img_dir / img_path.name
            img_pil.save(output_img_path)
            print(f"{img_path.name} 检测结果图片已保存到 {output_img_path}")






接口代码


from ultralytics import YOLO
from flask import Flask, request, jsonify
import base64
import tempfile
import os

# 加载模型(只加载一次,避免多次加载)
model = YOLO('best.pt')

def get_matched_points(img_path):
    """
    输入图片路径,返回匹配到的3个点的中心坐标 [(cx1, cy1), (cx2, cy2), (cx3, cy3)]
    若未检测到3个点,返回空列表
    """
    results = model(img_path)
    for r in results:
        if hasattr(r, 'boxes') and r.boxes is not None and len(r.boxes) > 0:
            all_targets = []  # [(cx, cy, idx, [x1, y1, x2, y2], class_id)]
            for idx, box in enumerate(r.boxes):
                x1, y1, x2, y2 = box.xyxy[0].tolist()
                cx = (x1 + x2) / 2
                cy = (y1 + y2) / 2
                class_id = int(box.cls[0].item()) if hasattr(box, 'cls') else -1
                all_targets.append((cx, cy, idx, [x1, y1, x2, y2], class_id))
            bottom3 = sorted(all_targets, key=lambda x: -x[1])[:3
            bottom3 = sorted(bottom3, key=lambda x: x[0])
            matched_top = []
            used_top_idx = set()
            for b in bottom3:
                bx, by, bidx, bbox, bcls = b
                candidates = [t for t in all_targets if t[1 < by and t[4 == bcls and t[2 not in used_top_idx
                if not candidates:
                    continue
                best_top = min(candidates, key=lambda t: abs(t[0 - bx))
                matched_top.append(best_top)
                used_top_idx.add(best_top[2])
            if len(matched_top) == 3:
                return [(int(cx), int(cy)) for (cx, cy, *_ ) in matched_top
    return []  # 未检测到3个点

app = Flask(__name__)

@app.route('/get_points', methods=['POST'])
def get_points():
    data = request.get_json()
    img_base64 = data.get('img_base64', '')
    if not img_base64:
        return jsonify({'error': 'No img_base64 provided'}), 400
    # 解码base64并保存为临时文件
    try:
        img_bytes = base64.b64decode(img_base64)
        with tempfile.NamedTemporaryFile(delete=False, suffix='.bmp') as tmp_file:
            tmp_file.write(img_bytes)
            tmp_img_path = tmp_file.name
        points = get_matched_points(tmp_img_path)
        os.remove(tmp_img_path)
        return jsonify({'points': points})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1214, debug=True)
测试代码
import requests
import base64

# 读取本地图片并编码为base64
with open("images/00ad74af33c2700b5db5b7bf6adbddf9.bmp", "rb") as f:
    img_base64 = base64.b64encode(f.read()).decode()

# 构造请求数据
data = {
    "img_base64": img_base64
}

# 发送POST请求
response = requests.post("http://127.0.0.1:1214/get_points", json=data)

# 输出返回结果
print(response.json())







模型下载地址:[color=rgba(0, 0, 0, 0.85)]https://www.123865.com/s/oY0iVv-WXqyh







1752052297231.jpg

结帖率:71% (5/7)

签到天数: 5 天

 楼主| 发表于 前天 14:11 | 显示全部楼层   重庆市重庆市
.pt onnx ncnn 三种模型都打包了 自取
回复 支持 反对

使用道具 举报

结帖率:88% (15/17)

签到天数: 7 天

发表于 前天 16:02 | 显示全部楼层   广东省广州市
这是谁的部将
回复 支持 反对

使用道具 举报

结帖率:71% (5/7)

签到天数: 5 天

 楼主| 发表于 前天 14:11 | 显示全部楼层   重庆市重庆市
.pt onnx ncnn 三种模型都打包了 自取
回复 支持 反对

使用道具 举报

签到天数: 8 天

发表于 前天 13:02 | 显示全部楼层   福建省南平市
本帖最后由 wdh1991 于 2025-7-10 13:03 编辑

666666666666666 不转 onnx 模型
回复 支持 反对

使用道具 举报

结帖率:0% (0/1)

签到天数: 2 天

发表于 前天 10:23 | 显示全部楼层   浙江省杭州市
支持一下。
回复 支持 反对

使用道具 举报

结帖率:0% (0/2)

签到天数: 11 天

发表于 前天 08:49 | 显示全部楼层   广西壮族自治区玉林市
感谢分享
回复 支持 反对

使用道具 举报

结帖率:100% (1/1)

签到天数: 4 天

发表于 前天 01:48 高大上手机用户 | 显示全部楼层   湖南省长沙市
在分享个tx点选的算法,哈哈哈哈
回复 支持 反对

使用道具 举报

结帖率:100% (1/1)

签到天数: 12 天

发表于 3 天前 | 显示全部楼层   湖南省邵阳市
加油!努力学习!
回复 支持 反对

使用道具 举报

签到天数: 7 天

发表于 3 天前 | 显示全部楼层   广东省惠州市
加油!努力学习!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 致发广告者

发布主题 收藏帖子 返回列表

sitemap| 易语言源码| 易语言教程| 易语言论坛| 易语言模块| 手机版| 广告投放| 精易论坛
拒绝任何人以任何形式在本论坛发表与中华人民共和国法律相抵触的言论,本站内容均为会员发表,并不代表精易立场!
论坛帖子内容仅用于技术交流学习和研究的目的,严禁用于非法目的,否则造成一切后果自负!如帖子内容侵害到你的权益,请联系我们!
防范网络诈骗,远离网络犯罪 违法和不良信息举报QQ: 793400750,邮箱:wp@125.la
网站简介:精易论坛成立于2009年,是一个程序设计学习交流技术论坛,隶属于揭阳市揭东区精易科技有限公司所有。
Powered by Discuz! X3.4 揭阳市揭东区精易科技有限公司 ( 粤ICP备12094385号-1) 粤公网安备 44522102000125 增值电信业务经营许可证 粤B2-20192173

快速回复 返回顶部 返回列表