point.html 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>YOLO图片标注工具</title>
  6. <style>
  7. body { font-family: Arial, sans-serif; margin: 0; background: #f7f7f7; }
  8. #main-container {
  9. display: flex;
  10. height: 100vh;
  11. }
  12. #left-panel {
  13. width: 220px;
  14. background: #fff;
  15. border-right: 1px solid #eee;
  16. padding: 20px 10px 10px 10px;
  17. box-sizing: border-box;
  18. display: flex;
  19. flex-direction: column;
  20. }
  21. #imgList {
  22. flex: 1;
  23. overflow-y: auto;
  24. margin-top: 10px;
  25. }
  26. .img-url-item {
  27. padding: 6px 8px;
  28. border-radius: 4px;
  29. cursor: pointer;
  30. margin-bottom: 4px;
  31. transition: background 0.2s;
  32. }
  33. .img-url-item.active, .img-url-item:hover {
  34. background: #e6f7ff;
  35. }
  36. #center-panel {
  37. flex: 1;
  38. display: block;
  39. min-height: 600px;
  40. height: 100%;
  41. background: #f5f5f5;
  42. box-sizing: border-box;
  43. }
  44. .canvas-wrapper {
  45. width: 900px;
  46. height: 600px;
  47. background: #f5f5f5;
  48. position: relative;
  49. overflow: hidden;
  50. margin: 0 auto;
  51. display: block;
  52. }
  53. #canvas {
  54. border: 1px solid #ccc;
  55. cursor: crosshair;
  56. background: #acacac;
  57. box-shadow: 0 2px 8px #222;
  58. display: block;
  59. width: 900px;
  60. height: 600px;
  61. /* 宽高固定 */
  62. }
  63. #controls {
  64. margin-bottom: 10px;
  65. width: 100%;
  66. display: flex;
  67. gap: 8px;
  68. justify-content: center;
  69. }
  70. #right-panel {
  71. width: 260px;
  72. background: #fff;
  73. border-left: 1px solid #eee;
  74. padding: 20px 10px 10px 10px;
  75. box-sizing: border-box;
  76. display: flex;
  77. flex-direction: column;
  78. }
  79. #boxes-list {
  80. margin-top: 10px;
  81. flex: 1;
  82. overflow-y: auto;
  83. }
  84. .box-item {
  85. font-size: 14px;
  86. background: #f5f5f5;
  87. margin-bottom: 6px;
  88. padding: 6px 8px;
  89. border-radius: 4px;
  90. display: flex;
  91. justify-content: space-between;
  92. align-items: center;
  93. }
  94. .box-item.active {
  95. background: #ffe58f;
  96. border: 1.5px solid #faad14;
  97. }
  98. .del-btn {
  99. background: #ff7875;
  100. color: #fff;
  101. border: none;
  102. border-radius: 3px;
  103. padding: 2px 8px;
  104. cursor: pointer;
  105. font-size: 12px;
  106. }
  107. .del-btn:hover {
  108. background: #d9363e;
  109. }
  110. #exportBtn {
  111. margin-top: 10px;
  112. width: 100%;
  113. background: #1890ff;
  114. color: #fff;
  115. border: none;
  116. border-radius: 4px;
  117. padding: 8px 0;
  118. font-size: 15px;
  119. cursor: pointer;
  120. }
  121. #exportBtn:disabled {
  122. background: #ccc;
  123. color: #fff;
  124. cursor: not-allowed;
  125. }
  126. h2 { margin: 0 0 18px 0; text-align: center; }
  127. #imgUrlInput { width: 100%; box-sizing: border-box; }
  128. #loadImgBtn { width: 100%; }
  129. .img-thumb {
  130. width: 100%;
  131. max-width: 180px;
  132. height: 90px;
  133. object-fit: cover;
  134. border-radius: 6px;
  135. border: 2px solid transparent;
  136. margin-bottom: 8px;
  137. cursor: pointer;
  138. transition: border 0.2s;
  139. background: #f0f0f0;
  140. }
  141. .img-thumb.active {
  142. border: 2px solid #1890ff;
  143. }
  144. </style>
  145. <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  146. </head>
  147. <body>
  148. <div id="main-container">
  149. <!-- 左侧图片列表 -->
  150. <div id="left-panel">
  151. <h2>图片列表</h2>
  152. <div id="imgList"></div>
  153. </div>
  154. <!-- 中间标注区 -->
  155. <div id="center-panel">
  156. <h2>图片标注区</h2>
  157. <div id="zoom-controls" style="margin:18px 0 10px 0;display:flex;gap:8px;justify-content:center;">
  158. <button id="prevImgBtn" style="padding:6px 18px;font-size:15px;border-radius:4px;border:none;background:#1890ff;color:#fff;cursor:pointer;">上一张</button>
  159. <button id="zoomInBtn" style="padding:4px 14px;">放大</button>
  160. <button id="zoomOutBtn" style="padding:4px 14px;">缩小</button>
  161. <button id="zoomResetBtn" style="padding:4px 14px;">重置</button>
  162. <button id="nextImgBtn" style="padding:6px 18px;font-size:15px;border-radius:4px;border:none;background:#1890ff;color:#fff;cursor:pointer;">下一张</button>
  163. </div>
  164. <div class="canvas-wrapper">
  165. <canvas id="canvas"></canvas>
  166. <div id="coordTip" style="position:fixed;display:none;pointer-events:none;z-index:9999;font-size:12px;color:#fff;background:rgba(0,0,0,0.7);padding:1px 6px;border-radius:4px;"></div>
  167. </div>
  168. </div>
  169. <!-- 右侧标注结果 -->
  170. <div id="right-panel">
  171. <h2>标注结果</h2>
  172. <div style="margin-bottom:10px;">
  173. <label for="classSelect">分类:</label>
  174. <select id="classSelect" style="font-size:15px;padding:2px 8px;">
  175. <!-- 动态生成选项 -->
  176. </select>
  177. </div>
  178. <div id="boxes-list"></div>
  179. <button id="clearBoxesBtn" style="width:100%;margin-bottom:10px;background:#ff7875;color:#fff;border:none;border-radius:4px;padding:8px 0;font-size:15px;cursor:pointer;">清空所有标记</button>
  180. <button id="exportBtn" disabled style="margin-top:0;">导出YOLO标注</button>
  181. </div>
  182. </div>
  183. <script>
  184. // -------------------- 全局变量定义 --------------------
  185. let img = new window.Image(); // 当前加载的图片对象
  186. let boxes = []; // 当前图片的所有标注框数组
  187. let drawing = false; // 是否正在绘制新框
  188. let startX = 0, startY = 0, endX = 0, endY = 0; // 新建框的起止点(图片坐标)
  189. let imgWidth = 0, imgHeight = 0; // 当前图片的原始宽高
  190. let selectedBoxIndex = -1; // 当前选中的框索引
  191. let dragMode = null; // 拖动模式:null/move/resize
  192. let dragOffsetX = 0, dragOffsetY = 0; // 拖动时鼠标与框左上角的偏移
  193. const HANDLE_SIZE = 10; // 手柄的像素大小
  194. // 8个手柄类型,分别对应四个角和四条边中点
  195. const HANDLE_TYPES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
  196. // 缩放相关
  197. let imgScale = 1.0; // 图片缩放比例
  198. let minImgScale = 0.2, maxImgScale = 5.0; // 缩放上下限
  199. let imgOffsetX = 0, imgOffsetY = 0; // 图片在canvas内的平移
  200. let baseScale = 1.0; // 图片全图自适应时的缩放比例
  201. let spacePressed = false; // 是否按下空格
  202. let isPanning = false; // 是否正在拖动画布
  203. let panStart = {x: 0, y: 0}; // 拖动画布起点
  204. let panOffsetStart = {x: 0, y: 0}; // 拖动画布时的初始偏移
  205. // 分类配置:名称和颜色
  206. const classConfig = [
  207. { index: 0, name: 'cat', border: '#e67e22' }, // 橙色
  208. { index: 1, name: 'chicken',border: '#f1c40f' }, // 黄色
  209. { index: 2, name: 'cow', border: '#95a5a6' }, // 灰色
  210. { index: 3, name: 'dog', border: '#2980b9' }, // 蓝色
  211. { index: 4, name: 'fox', border: '#d35400' }, // 深橙
  212. { index: 5, name: 'goat', border: '#16a085' }, // 青色
  213. { index: 6, name: 'horse', border: '#8e44ad' }, // 紫色
  214. { index: 7, name: 'person', border: '#e74c3c' }, // 红色
  215. { index: 8, name: 'racoon', border: '#34495e' }, // 深蓝灰
  216. { index: 9, name: 'skunk', border: '#2c3e50' } // 深灰
  217. ];
  218. // 辅助函数:将hex色转为rgba字符串,a为透明度
  219. function hexToRgba(hex, a) {
  220. hex = hex.replace('#', '');
  221. if (hex.length === 3) {
  222. hex = hex.split('').map(x => x + x).join('');
  223. }
  224. const r = parseInt(hex.substring(0,2), 16);
  225. const g = parseInt(hex.substring(2,4), 16);
  226. const b = parseInt(hex.substring(4,6), 16);
  227. return `rgba(${r},${g},${b},${a})`;
  228. }
  229. // -------------------- 工具函数 --------------------
  230. // 判断点(x, y)是否在框box内部(图片坐标)
  231. function isInBox(x, y, box) {
  232. return x >= box.x && x <= box.x + box.w && y >= box.y && y <= box.y + box.h;
  233. }
  234. // 获取8个手柄的中心坐标(用于缩放)
  235. function getHandles(box, size) {
  236. const x = box.x, y = box.y, w = box.w, h = box.h;
  237. const hs = (size || HANDLE_SIZE) / 2;
  238. return {
  239. nw: { x: x - hs, y: y - hs }, // 左上角
  240. n: { x: x + w/2 - hs, y: y - hs }, // 上中
  241. ne: { x: x + w - hs, y: y - hs }, // 右上角
  242. e: { x: x + w - hs, y: y + h/2 - hs }, // 右中
  243. se: { x: x + w - hs, y: y + h - hs }, // 右下角
  244. s: { x: x + w/2 - hs, y: y + h - hs }, // 下中
  245. sw: { x: x - hs, y: y + h - hs }, // 左下角
  246. w: { x: x - hs, y: y + h/2 - hs } // 左中
  247. };
  248. }
  249. // 判断点(x, y)是否在某个手柄上,返回手柄类型(canvas坐标)
  250. function getHandleAt(x, y, box) {
  251. let domW = $('#canvas').width();
  252. let pixelRatio = $('#canvas')[0].width / domW;
  253. let handleSize = 10 * pixelRatio;
  254. const handles = getHandles(box, handleSize);
  255. for (let type of HANDLE_TYPES) {
  256. const hx = handles[type].x, hy = handles[type].y;
  257. if (x >= hx && x <= hx + handleSize && y >= hy && y <= hy + handleSize) {
  258. return type;
  259. }
  260. }
  261. return null;
  262. }
  263. // 根据手柄类型设置鼠标指针样式
  264. function setCursorByHandle(type) {
  265. const map = {
  266. nw: 'nwse-resize',
  267. se: 'nwse-resize',
  268. ne: 'nesw-resize',
  269. sw: 'nesw-resize',
  270. n: 'ns-resize',
  271. s: 'ns-resize',
  272. e: 'ew-resize',
  273. w: 'ew-resize'
  274. };
  275. $('#canvas').css('cursor', map[type] || 'default');
  276. }
  277. // -------------------- 绘制函数 --------------------
  278. // 负责绘制图片、所有标注框、选中框的手柄、正在绘制的新框
  279. function drawAll() {
  280. const ctx = $('#canvas')[0].getContext('2d');
  281. ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  282. ctx.save();
  283. const info = window._imgDrawInfo;
  284. if (info) {
  285. // 计算图片在canvas上的显示区域
  286. let drawW = info.imgWidth * imgScale;
  287. let drawH = info.imgHeight * imgScale;
  288. let drawX = (900 - drawW) / 2 + imgOffsetX;
  289. let drawY = (600 - drawH) / 2 + imgOffsetY;
  290. ctx.drawImage(img, drawX, drawY, drawW, drawH);
  291. }
  292. let lineWidth = 2;
  293. let handleSize = 10;
  294. // 绘制所有标注框
  295. boxes.forEach((box, idx) => {
  296. ctx.save();
  297. let c = toCanvasCoord(box.x, box.y); // 左上角canvas坐标
  298. let cw = box.w * imgScale;
  299. let ch = box.h * imgScale;
  300. // 先绘制半透明背景色和边框色,按分类区分
  301. if (idx === selectedBoxIndex) {
  302. ctx.fillStyle = 'rgba(255,200,0,0.18)'; // 选中填充
  303. ctx.strokeStyle = 'orange'; // 选中边框
  304. } else {
  305. const conf = classConfig.find(c => c.index === box.classId) || { border: 'red' };
  306. ctx.fillStyle = hexToRgba(conf.border, 0.18);
  307. ctx.strokeStyle = conf.border;
  308. }
  309. ctx.lineWidth = lineWidth;
  310. ctx.fillRect(c.x, c.y, cw, ch);
  311. ctx.strokeRect(c.x, c.y, cw, ch);
  312. // 绘制选中框的8个手柄
  313. if (idx === selectedBoxIndex) {
  314. ctx.fillStyle = 'blue';
  315. const handles = getHandles({x: c.x, y: c.y, w: cw, h: ch}, handleSize);
  316. for (let type of HANDLE_TYPES) {
  317. ctx.fillRect(handles[type].x, handles[type].y, handleSize, handleSize);
  318. }
  319. }
  320. ctx.restore();
  321. });
  322. // 绘制正在新建的框
  323. if (drawing) {
  324. ctx.strokeStyle = 'blue';
  325. ctx.lineWidth = lineWidth;
  326. let c1 = toCanvasCoord(startX, startY);
  327. let c2 = toCanvasCoord(endX, endY);
  328. ctx.strokeRect(
  329. Math.min(c1.x, c2.x),
  330. Math.min(c1.y, c2.y),
  331. Math.abs(c2.x - c1.x),
  332. Math.abs(c2.y - c1.y)
  333. );
  334. }
  335. ctx.restore();
  336. }
  337. // -------------------- 右侧标注框列表渲染 --------------------
  338. // 渲染右侧标注框列表,并高亮选中项
  339. function updateBoxesList() {
  340. let html = '';
  341. boxes.forEach((box, idx) => {
  342. const active = (idx === selectedBoxIndex) ? ' active' : '';
  343. html += `<div class="box-item${active}">
  344. ${idx+1}
  345. <select class='class-select' data-idx='${idx}' style='font-size:13px;padding:1px 6px;'>
  346. ${classConfig.map(c => `<option value="${c.index}"${box.classId==c.index?' selected':''}>${c.name}</option>`).join('')}
  347. </select>
  348. <button data-idx="${idx}" class="del-btn">删除</button>
  349. </div>`;
  350. });
  351. $('#boxes-list').html(html);
  352. $('#exportBtn').prop('disabled', boxes.length === 0);
  353. }
  354. // -------------------- 坐标换算函数 --------------------
  355. // canvas坐标转图片坐标
  356. function toImageCoord(canvasX, canvasY) {
  357. const info = window._imgDrawInfo;
  358. if (!info) return {x: 0, y: 0};
  359. let drawW = info.imgWidth * imgScale;
  360. let drawH = info.imgHeight * imgScale;
  361. let drawX = (900 - drawW) / 2 + imgOffsetX;
  362. let drawY = (600 - drawH) / 2 + imgOffsetY;
  363. let x = (canvasX - drawX) / imgScale;
  364. let y = (canvasY - drawY) / imgScale;
  365. return {x, y};
  366. }
  367. // 图片坐标转canvas坐标
  368. function toCanvasCoord(imgX, imgY) {
  369. const info = window._imgDrawInfo;
  370. if (!info) return {x: 0, y: 0};
  371. let drawW = info.imgWidth * imgScale;
  372. let drawH = info.imgHeight * imgScale;
  373. let drawX = (900 - drawW) / 2 + imgOffsetX;
  374. let drawY = (600 - drawH) / 2 + imgOffsetY;
  375. let x = imgX * imgScale + drawX;
  376. let y = imgY * imgScale + drawY;
  377. return {x, y};
  378. }
  379. $(function() {
  380. // -------------------- 图片列表与mock数据 --------------------
  381. let imgUrlArr = [
  382. {
  383. id: 'img1',
  384. url: 'train/images/1_jpg.rf.5c86eb65dfbf1ec4e2fc4830270f2e16.jpg',
  385. boxes: [
  386. { classId: 4, x_center: 0.67734375, y_center: 0.5359375, width: 0.6453125, height: 0.88203125 }
  387. ]
  388. },
  389. {
  390. id: 'img2',
  391. url: 'train/images/2_jpg.rf.066043edad2696f90a613dda6f0d97c9.jpg',
  392. boxes: [
  393. { classId: 4, x_center: 0.5203125, y_center: 0.553125, width: 0.959375, height: 0.740625 }
  394. ]
  395. },
  396. {
  397. id: 'imgx',
  398. url: 'https://image.cszcyl.cn/coze/%E9%AB%98%E8%80%83%E5%BF%85%E8%83%9C-%E8%B6%85%E6%B8%85.png',
  399. boxes: [
  400. { classId: 3, x_center: 0.67734375, y_center: 0.5359375, width: 0.6453125, height: 0.88203125 }
  401. ]
  402. }
  403. ];
  404. let currentImgIndex = 0; // 当前图片索引
  405. // 渲染左侧图片缩略图列表
  406. function renderImgList() {
  407. let html = '';
  408. imgUrlArr.forEach((item, idx) => {
  409. html += `<img src="${item.url}" class="img-thumb${idx===currentImgIndex?' active':''}" data-idx="${idx}" title="${item.url}">`;
  410. });
  411. $('#imgList').html(html);
  412. // 渲染后自动滚动选中图片到可见区域并居中
  413. setTimeout(() => {
  414. const $active = $('#imgList .img-thumb.active')[0];
  415. if ($active) $active.scrollIntoView({ block: 'center', behavior: 'auto' });
  416. }, 0);
  417. }
  418. renderImgList();
  419. // 点击图片缩略图切换图片
  420. $('#imgList').on('click', '.img-thumb', function() {
  421. const idx = $(this).data('idx');
  422. if (currentImgIndex === idx) return;
  423. currentImgIndex = idx;
  424. renderImgList();
  425. loadCurrentImage();
  426. });
  427. // 加载当前选中图片到canvas,并初始化标注框
  428. function loadCurrentImage() {
  429. const imgObj = imgUrlArr[currentImgIndex];
  430. const url = imgObj.url;
  431. // 更新按钮禁用状态
  432. $('#prevImgBtn').prop('disabled', currentImgIndex === 0);
  433. $('#nextImgBtn').prop('disabled', currentImgIndex === imgUrlArr.length - 1);
  434. // 先解绑,防止多次触发
  435. img.onload = null;
  436. img.onerror = null;
  437. img.onload = function() {
  438. imgWidth = img.width;
  439. imgHeight = img.height;
  440. // 计算自适应缩放比例
  441. if (imgWidth <= 900 && imgHeight <= 600) {
  442. baseScale = 1;
  443. } else {
  444. baseScale = Math.min(900 / imgWidth, 600 / imgHeight);
  445. }
  446. imgScale = baseScale;
  447. imgOffsetX = 0;
  448. imgOffsetY = 0;
  449. window._imgDrawInfo = {imgWidth, imgHeight};
  450. $('#canvas').attr({ width: 900, height: 600 });
  451. $('#canvas').css({ width: '900px', height: '600px', margin: 0, padding: 0 });
  452. // 初始化标注框(YOLO格式转为画图用格式)
  453. boxes = (imgObj.boxes || []).map(box => {
  454. // YOLO: {classId, x_center, y_center, width, height}
  455. const x = (box.x_center - box.width/2) * imgWidth;
  456. const y = (box.y_center - box.height/2) * imgHeight;
  457. const w = box.width * imgWidth;
  458. const h = box.height * imgHeight;
  459. return { x, y, w, h, classId: box.classId };
  460. });
  461. selectedBoxIndex = -1;
  462. drawAll();
  463. updateBoxesList();
  464. };
  465. img.onerror = function() {
  466. alert('图片加载失败,请检查URL是否正确');
  467. };
  468. img.src = url;
  469. }
  470. // 页面加载时自动加载第一张图片
  471. loadCurrentImage();
  472. let resizeHandle = null; // 当前正在拖动的手柄类型
  473. // 监听键盘空格按下/松开(用于画布拖动)
  474. $(document).on('keydown', function(e) {
  475. if (e.code === 'Space') spacePressed = true;
  476. });
  477. $(document).on('keyup', function(e) {
  478. if (e.code === 'Space') spacePressed = false;
  479. });
  480. // -------------------- canvas鼠标事件 --------------------
  481. // 鼠标按下事件
  482. $('#canvas').on('mousedown', function(e) {
  483. if (!imgWidth) return;
  484. const rect = this.getBoundingClientRect();
  485. const canvasX = e.clientX - rect.left;
  486. const canvasY = e.clientY - rect.top;
  487. // 新增:空格+左键 或 右键拖动画布
  488. if ((spacePressed && e.button === 0) || e.button === 2) {
  489. isPanning = true;
  490. panStart = {x: e.clientX, y: e.clientY};
  491. panOffsetStart = {x: imgOffsetX, y: imgOffsetY};
  492. $('#canvas').css('cursor', 'grab');
  493. return;
  494. }
  495. let found = false;
  496. resizeHandle = null;
  497. // 优先判断是否点中手柄或框(全部用canvas坐标判定)
  498. for (let i = boxes.length - 1; i >= 0; i--) {
  499. let cbox = toCanvasCoord(boxes[i].x, boxes[i].y);
  500. let cw = boxes[i].w * imgScale;
  501. let ch = boxes[i].h * imgScale;
  502. const handleType = getHandleAt(canvasX, canvasY, {x: cbox.x, y: cbox.y, w: cw, h: ch});
  503. if (handleType) {
  504. selectedBoxIndex = i;
  505. dragMode = 'resize';
  506. resizeHandle = handleType;
  507. found = true;
  508. break;
  509. } else if (
  510. canvasX >= cbox.x && canvasX <= cbox.x + cw &&
  511. canvasY >= cbox.y && canvasY <= cbox.y + ch
  512. ) {
  513. selectedBoxIndex = i;
  514. dragMode = 'move';
  515. dragOffsetX = toImageCoord(canvasX, canvasY).x - boxes[i].x;
  516. dragOffsetY = toImageCoord(canvasX, canvasY).y - boxes[i].y;
  517. found = true;
  518. break;
  519. }
  520. }
  521. if (found) {
  522. drawing = false;
  523. } else {
  524. // 没点中任何框,开始新建或取消选中
  525. selectedBoxIndex = -1;
  526. // 新建时,只有初始点在图片区域内才允许框选
  527. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  528. if (mouseX >= 0 && mouseX <= imgWidth && mouseY >= 0 && mouseY <= imgHeight) {
  529. drawing = true;
  530. startX = mouseX;
  531. startY = mouseY;
  532. endX = mouseX;
  533. endY = mouseY;
  534. }
  535. }
  536. // 无论如何都刷新一次,保证视觉同步
  537. drawAll();
  538. updateBoxesList();
  539. });
  540. // 鼠标移动事件
  541. $('#canvas').on('mousemove', function(e) {
  542. const rect = this.getBoundingClientRect();
  543. const canvasX = e.clientX - rect.left;
  544. const canvasY = e.clientY - rect.top;
  545. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  546. // 实时显示坐标
  547. if (imgWidth) {
  548. let showX = Math.round(mouseX);
  549. let showY = Math.round(mouseY);
  550. if (showX >= 0 && showX <= imgWidth && showY >= 0 && showY <= imgHeight) {
  551. $('#coordTip').text(`${showX}, ${showY}`).css({
  552. left: (e.clientX - 10) + 'px',
  553. top: (e.clientY - 28) + 'px',
  554. display: 'block'
  555. });
  556. } else {
  557. $('#coordTip').hide();
  558. }
  559. }
  560. // 新增:画布拖拽
  561. if (isPanning) {
  562. let dx = e.clientX - panStart.x;
  563. let dy = e.clientY - panStart.y;
  564. imgOffsetX = panOffsetStart.x + dx;
  565. imgOffsetY = panOffsetStart.y + dy;
  566. drawAll();
  567. return;
  568. }
  569. if (drawing) {
  570. // 新建框时,动态绘制,限制不出界
  571. endX = Math.max(0, Math.min(mouseX, imgWidth));
  572. endY = Math.max(0, Math.min(mouseY, imgHeight));
  573. drawAll();
  574. } else if (selectedBoxIndex !== -1 && dragMode) {
  575. let box = boxes[selectedBoxIndex];
  576. let minW = 10, minH = 10;
  577. let x = box.x, y = box.y, w = box.w, h = box.h;
  578. if (dragMode === 'move') {
  579. // 拖动移动框
  580. let newX = mouseX - dragOffsetX;
  581. let newY = mouseY - dragOffsetY;
  582. newX = Math.max(0, Math.min(newX, imgWidth - w));
  583. newY = Math.max(0, Math.min(newY, imgHeight - h));
  584. box.x = newX;
  585. box.y = newY;
  586. } else if (dragMode === 'resize' && resizeHandle) {
  587. // 8方向缩放
  588. switch (resizeHandle) {
  589. case 'nw': // 左上角
  590. box.x = Math.min(mouseX, x + w - minW);
  591. box.y = Math.min(mouseY, y + h - minH);
  592. box.w = w + (x - box.x);
  593. box.h = h + (y - box.y);
  594. break;
  595. case 'n': // 上中
  596. box.y = Math.min(mouseY, y + h - minH);
  597. box.h = h + (y - box.y);
  598. break;
  599. case 'ne': // 右上角
  600. box.y = Math.min(mouseY, y + h - minH);
  601. box.w = Math.max(minW, mouseX - x);
  602. box.h = h + (y - box.y);
  603. break;
  604. case 'e': // 右中
  605. box.w = Math.max(minW, mouseX - x);
  606. break;
  607. case 'se': // 右下角
  608. box.w = Math.max(minW, mouseX - x);
  609. box.h = Math.max(minH, mouseY - y);
  610. break;
  611. case 's': // 下中
  612. box.h = Math.max(minH, mouseY - y);
  613. break;
  614. case 'sw': // 左下角
  615. box.x = Math.min(mouseX, x + w - minW);
  616. box.w = w + (x - box.x);
  617. box.h = Math.max(minH, mouseY - y);
  618. break;
  619. case 'w': // 左中
  620. box.x = Math.min(mouseX, x + w - minW);
  621. box.w = w + (x - box.x);
  622. break;
  623. }
  624. // 限制不出界
  625. if (box.x < 0) { box.w += box.x; box.x = 0; }
  626. if (box.y < 0) { box.h += box.y; box.y = 0; }
  627. if (box.x + box.w > imgWidth) box.w = imgWidth - box.x;
  628. if (box.y + box.h > imgHeight) box.h = imgHeight - box.y;
  629. }
  630. drawAll();
  631. updateBoxesList();
  632. } else if (selectedBoxIndex !== -1) {
  633. // 悬停手柄时改变鼠标样式
  634. const box = boxes[selectedBoxIndex];
  635. const handleType = getHandleAt(mouseX, mouseY, box);
  636. setCursorByHandle(handleType);
  637. } else {
  638. $('#canvas').css('cursor', 'crosshair');
  639. }
  640. });
  641. // 鼠标松开事件
  642. $(document).on('mouseup', function(e) {
  643. if (isPanning) {
  644. isPanning = false;
  645. $('#canvas').css('cursor', spacePressed ? 'grab' : 'crosshair');
  646. return;
  647. }
  648. const rect = $('#canvas')[0].getBoundingClientRect();
  649. const canvasX = e.clientX - rect.left;
  650. const canvasY = e.clientY - rect.top;
  651. const {x: mouseX, y: mouseY} = toImageCoord(canvasX, canvasY);
  652. if (drawing) {
  653. drawing = false;
  654. // 重新用toImageCoord获取endX、endY,保证为图片原始坐标
  655. endX = Math.max(0, Math.min(mouseX, imgWidth));
  656. endY = Math.max(0, Math.min(mouseY, imgHeight));
  657. const x = Math.max(0, Math.min(startX, endX));
  658. const y = Math.max(0, Math.min(startY, endY));
  659. let w = Math.abs(endX - startX);
  660. let h = Math.abs(endY - startY);
  661. // 再次限制宽高不超界
  662. if (x + w > imgWidth) w = imgWidth - x;
  663. if (y + h > imgHeight) h = imgHeight - y;
  664. if (w > 5 && h > 5) {
  665. // 新建框时用当前分类
  666. const classId = parseInt($('#classSelect').val(), 10);
  667. boxes.push({ x, y, w, h, classId });
  668. selectedBoxIndex = boxes.length - 1;
  669. syncBoxesToYOLO();
  670. }
  671. drawAll();
  672. updateBoxesList();
  673. }
  674. dragMode = null;
  675. resizeHandle = null;
  676. });
  677. // 删除按钮事件
  678. $('#boxes-list').on('click', '.del-btn', function() {
  679. const idx = $(this).data('idx');
  680. boxes.splice(idx, 1);
  681. if (selectedBoxIndex === idx) selectedBoxIndex = -1;
  682. drawAll();
  683. updateBoxesList();
  684. syncBoxesToYOLO();
  685. });
  686. // 支持选中边框时按Delete键删除
  687. $(document).on('keydown', function(e) {
  688. if ((e.key === 'Delete' || e.key === 'Backspace') && selectedBoxIndex !== -1 && boxes.length > 0) {
  689. boxes.splice(selectedBoxIndex, 1);
  690. selectedBoxIndex = -1;
  691. drawAll();
  692. updateBoxesList();
  693. syncBoxesToYOLO();
  694. }
  695. });
  696. // 右侧标注项点击选中,联动canvas高亮
  697. $('#boxes-list').on('click', '.box-item', function(e) {
  698. // 避免点击删除按钮或下拉框时触发
  699. if (
  700. $(e.target).hasClass('del-btn') ||
  701. $(e.target).hasClass('class-select') ||
  702. e.target.tagName === 'SELECT' ||
  703. e.target.tagName === 'OPTION'
  704. ) return;
  705. const idx = $(this).index();
  706. selectedBoxIndex = idx;
  707. drawAll();
  708. updateBoxesList();
  709. });
  710. // 右侧分类下拉框修改事件
  711. $('#boxes-list').on('change', '.class-select', function() {
  712. const idx = $(this).data('idx');
  713. const val = parseInt($(this).val(), 10);
  714. if (boxes[idx]) {
  715. boxes[idx].classId = val;
  716. updateBoxesList();
  717. drawAll();
  718. syncBoxesToYOLO();
  719. }
  720. });
  721. // -------------------- 导出/清空/缩放/切换图片等事件 --------------------
  722. // 将 boxes(画图用格式)同步回 imgUrlArr 的 YOLO 格式
  723. function syncBoxesToYOLO() {
  724. imgUrlArr[currentImgIndex].boxes = boxes.map(box => {
  725. const x_center = (box.x + box.w/2) / imgWidth;
  726. const y_center = (box.y + box.h/2) / imgHeight;
  727. const width = box.w / imgWidth;
  728. const height = box.h / imgHeight;
  729. return {
  730. classId: box.classId,
  731. x_center: x_center,
  732. y_center: y_center,
  733. width: width,
  734. height: height
  735. };
  736. });
  737. }
  738. // 导出YOLO格式标注
  739. $('#exportBtn').on('click', function() {
  740. // 直接导出 imgUrlArr[currentImgIndex].boxes
  741. let lines = (imgUrlArr[currentImgIndex].boxes || []).map(box => {
  742. return `${box.classId} ${box.x_center} ${box.y_center} ${box.width} ${box.height}`;
  743. });
  744. const blob = new Blob([lines.join('\n')], { type: 'text/plain' });
  745. const a = document.createElement('a');
  746. a.href = URL.createObjectURL(blob);
  747. a.download = 'labels.txt';
  748. a.click();
  749. });
  750. // 清空所有标记按钮
  751. $('#clearBoxesBtn').on('click', function() {
  752. boxes = [];
  753. drawAll();
  754. updateBoxesList();
  755. syncBoxesToYOLO();
  756. });
  757. // 放大缩小按钮事件
  758. $('#zoomInBtn').on('click', function() {
  759. imgScale = Math.min(maxImgScale, imgScale * 1.2);
  760. drawAll();
  761. });
  762. $('#zoomOutBtn').on('click', function() {
  763. imgScale = Math.max(minImgScale, imgScale / 1.2);
  764. drawAll();
  765. });
  766. $('#zoomResetBtn').on('click', function() {
  767. imgScale = baseScale;
  768. imgOffsetX = 0;
  769. imgOffsetY = 0;
  770. drawAll();
  771. });
  772. // 鼠标滚轮缩放(以鼠标为中心)
  773. $('#canvas').on('wheel', function(e) {
  774. e.preventDefault();
  775. let mouseX = e.offsetX, mouseY = e.offsetY;
  776. // 1. 记录缩放前鼠标在图片上的坐标
  777. let before = toImageCoord(mouseX, mouseY);
  778. // 2. 计算缩放
  779. if (e.originalEvent.deltaY < 0) {
  780. imgScale = Math.min(maxImgScale, imgScale * 1.1);
  781. } else {
  782. imgScale = Math.max(minImgScale, imgScale / 1.1);
  783. }
  784. // 3. 计算缩放后该点在canvas上的新位置
  785. let after = toCanvasCoord(before.x, before.y);
  786. // 4. 调整offset,使鼠标下的图片点不动
  787. imgOffsetX += (mouseX - after.x);
  788. imgOffsetY += (mouseY - after.y);
  789. drawAll();
  790. });
  791. // 禁止右键菜单弹出
  792. $('#canvas').on('contextmenu', function(e) { e.preventDefault(); });
  793. // 鼠标移出canvas时隐藏坐标提示
  794. $('#canvas').on('mouseleave', function() {
  795. $('#coordTip').hide();
  796. });
  797. // 按钮切换上一张/下一张图片
  798. $('#prevImgBtn').on('click', function() {
  799. if (currentImgIndex > 0) {
  800. currentImgIndex--;
  801. renderImgList();
  802. loadCurrentImage();
  803. }
  804. });
  805. $('#nextImgBtn').on('click', function() {
  806. if (currentImgIndex < imgUrlArr.length - 1) {
  807. currentImgIndex++;
  808. renderImgList();
  809. loadCurrentImage();
  810. }
  811. });
  812. // 动态生成右侧分类下拉框选项
  813. function renderClassSelect() {
  814. let html = classConfig.map(c => `<option value="${c.index}">${c.name}</option>`).join('');
  815. $('#classSelect').html(html);
  816. }
  817. renderClassSelect();
  818. });
  819. </script>
  820. </body>
  821. </html>