-
Notifications
You must be signed in to change notification settings - Fork 172
Expand file tree
/
Copy pathgemini-bbox.html
More file actions
538 lines (467 loc) · 22.4 KB
/
gemini-bbox.html
File metadata and controls
538 lines (467 loc) · 22.4 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gemini API Image Bounding Box Visualization</title>
<script type="module">
import { GoogleGenerativeAI } from "https://esm.run/@google/generative-ai";
import { marked } from "https://esm.run/marked";
function getApiKey() {
let apiKey = localStorage.getItem("GEMINI_API_KEY");
if (!apiKey) {
apiKey = prompt("Please enter your Gemini API key:");
if (apiKey) {
localStorage.setItem("GEMINI_API_KEY", apiKey);
}
}
return apiKey;
}
async function getGenerativeModel(params) {
const API_KEY = getApiKey();
const genAI = new GoogleGenerativeAI(API_KEY);
return genAI.getGenerativeModel(params);
}
async function fileToGenerativePart(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve({
inlineData: {
data: reader.result.split(",")[1],
mimeType: file.type
}
});
reader.readAsDataURL(file);
});
}
function resizeAndCompressImage(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
if (width > 1000) {
height = Math.round((height * 1000) / width);
width = 1000;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(new File([blob], "compressed_image.jpg", { type: "image/jpeg" }));
}, 'image/jpeg', 0.7);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
}
async function processImageAndPrompt() {
const fileInput = document.getElementById('imageInput');
const promptInput = document.getElementById('promptInput');
const resultDiv = document.getElementById('result');
const modelSelect = document.getElementById('modelSelect');
if (!promptInput.value) {
alert('Please enter a prompt.');
return;
}
resultDiv.innerHTML = 'Processing...';
// Clear previous bounding box images
document.getElementById('boundingBoxImages').innerHTML = '';
try {
const model = await getGenerativeModel({ model: modelSelect.value });
let content = [promptInput.value];
if (fileInput.files[0]) {
const compressedImage = await resizeAndCompressImage(fileInput.files[0]);
const imagePart = await fileToGenerativePart(compressedImage);
content.push(imagePart);
}
const result = await model.generateContent(content);
const response = await result.response;
const text = response.text();
resultDiv.innerHTML = marked.parse(text);
if (fileInput.files[0]) {
// Extract coordinates from the response
const coordinates = extractCoordinates(text);
const points = extractPoints(text);
if (points.length > 0) {
displayImageWithPoints(fileInput.files[0], points);
} else if (coordinates.length > 0) {
displayImageWithBoundingBoxes(fileInput.files[0], coordinates);
}
}
} catch (error) {
resultDiv.innerHTML = `Error: ${error.message}`;
}
}
function extractCoordinates(text) {
const regex = /\[\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\]/g;
const matches = text.match(regex) || [];
return matches.map(JSON.parse);
}
function extractPoints(text) {
// Try to extract JSON array with point objects
try {
// Look for JSON array pattern
const jsonMatch = text.match(/\[[\s\S]*?\{"point"[\s\S]*?\](?=\s*$|\s*```|\s*\n\n)/);
if (jsonMatch) {
const parsed = JSON.parse(jsonMatch[0]);
if (Array.isArray(parsed) && parsed.length > 0 && parsed[0].point) {
return parsed;
}
}
} catch (e) {
// If parsing fails, return empty array
}
return [];
}
function displayImageWithBoundingBoxes(file, coordinates) {
const reader = new FileReader();
reader.onload = function(event) {
const image = new Image();
image.onload = function() {
const canvas = document.getElementById('canvas');
canvas.width = image.width + 100;
canvas.height = image.height + 100;
const ctx = canvas.getContext('2d');
// Draw the image
ctx.drawImage(image, 80, 20);
// Draw grid lines
ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'; // Red with 50% opacity
ctx.lineWidth = 1;
// Vertical grid lines
for (let i = 0; i <= 1000; i += 100) {
const x = 80 + i / 1000 * image.width;
ctx.beginPath();
ctx.moveTo(x, 20);
ctx.lineTo(x, image.height + 20);
ctx.stroke();
}
// Horizontal grid lines
for (let i = 0; i <= 1000; i += 100) {
const y = 20 + (1000 - i) / 1000 * image.height;
ctx.beginPath();
ctx.moveTo(80, y);
ctx.lineTo(image.width + 80, y);
ctx.stroke();
}
// Draw bounding boxes
const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
const boundingBoxImages = document.getElementById('boundingBoxImages');
boundingBoxImages.innerHTML = ''; // Clear previous bounding box images
coordinates.forEach((box, index) => {
const [ymin, xmin, ymax, xmax] = box.map(coord => coord / 1000);
const width = (xmax - xmin) * image.width;
const height = (ymax - ymin) * image.height;
ctx.strokeStyle = colors[index % colors.length];
ctx.lineWidth = 5;
ctx.strokeRect(xmin * image.width + 80, ymin * image.height + 20, width, height);
// Extract bounding box image
const boundingBoxCanvas = document.createElement('canvas');
boundingBoxCanvas.width = width;
boundingBoxCanvas.height = height;
const bbCtx = boundingBoxCanvas.getContext('2d');
bbCtx.drawImage(image, xmin * image.width, ymin * image.height, width, height, 0, 0, width, height);
// Convert canvas to JPEG base64 data URI
const dataURI = boundingBoxCanvas.toDataURL('image/jpeg');
const boundingBoxContainer = document.createElement('div');
boundingBoxContainer.className = 'bounding-box-container';
const title = document.createElement('p');
title.textContent = `Bounding Box: [${box.join(', ')}]`;
boundingBoxContainer.appendChild(title);
const img = document.createElement('img');
img.src = dataURI;
boundingBoxContainer.appendChild(img);
boundingBoxImages.appendChild(boundingBoxContainer);
});
// Draw axes and labels
ctx.strokeStyle = '#000000';
ctx.lineWidth = 1;
ctx.font = '26px Arial';
ctx.textAlign = 'right';
// Y-axis
ctx.beginPath();
ctx.moveTo(80, 20);
ctx.lineTo(80, image.height + 20);
ctx.stroke();
// Y-axis labels and ticks
for (let i = 0; i <= 1000; i += 100) {
const y = 20 + i / 1000 * image.height;
ctx.fillText(i.toString(), 75, y + 5);
ctx.beginPath();
ctx.moveTo(75, y);
ctx.lineTo(80, y);
ctx.stroke();
}
// X-axis
ctx.beginPath();
ctx.moveTo(80, image.height + 20);
ctx.lineTo(image.width + 80, image.height + 20);
ctx.stroke();
// X-axis labels and ticks
ctx.textAlign = 'center';
for (let i = 0; i <= 1000; i += 100) {
const x = 80 + i / 1000 * image.width;
ctx.fillText(i.toString(), x, image.height + 40);
ctx.beginPath();
ctx.moveTo(x, image.height + 20);
ctx.lineTo(x, image.height + 25);
ctx.stroke();
}
};
image.src = event.target.result;
};
reader.readAsDataURL(file);
}
function displayImageWithPoints(file, points) {
const reader = new FileReader();
reader.onload = function(event) {
const image = new Image();
image.onload = function() {
const canvas = document.getElementById('canvas');
canvas.width = image.width + 100;
canvas.height = image.height + 100;
const ctx = canvas.getContext('2d');
// Draw the image
ctx.drawImage(image, 80, 20);
// Draw grid lines
ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'; // Red with 50% opacity
ctx.lineWidth = 1;
// Vertical grid lines
for (let i = 0; i <= 1000; i += 100) {
const x = 80 + i / 1000 * image.width;
ctx.beginPath();
ctx.moveTo(x, 20);
ctx.lineTo(x, image.height + 20);
ctx.stroke();
}
// Horizontal grid lines
for (let i = 0; i <= 1000; i += 100) {
const y = 20 + (1000 - i) / 1000 * image.height;
ctx.beginPath();
ctx.moveTo(80, y);
ctx.lineTo(image.width + 80, y);
ctx.stroke();
}
// Draw points
const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF'];
const boundingBoxImages = document.getElementById('boundingBoxImages');
boundingBoxImages.innerHTML = ''; // Clear previous content
points.forEach((item, index) => {
const [y, x] = item.point.map(coord => coord / 1000);
const label = item.label || '';
// Calculate pixel position
const pixelX = x * image.width + 80;
const pixelY = y * image.height + 20;
const color = colors[index % colors.length];
// Draw point as a circle
ctx.fillStyle = color;
ctx.strokeStyle = '#FFFFFF';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(pixelX, pixelY, 8, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
// Draw label background
ctx.font = 'bold 16px Arial';
const textMetrics = ctx.measureText(label);
const textWidth = textMetrics.width;
const textHeight = 16;
const padding = 4;
// Position label to the right of the point
const labelX = pixelX + 12;
const labelY = pixelY - 8;
ctx.fillStyle = 'rgba(0, 0, 0, 0.7)';
ctx.fillRect(labelX, labelY, textWidth + padding * 2, textHeight + padding);
// Draw label text
ctx.fillStyle = '#FFFFFF';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
ctx.fillText(label, labelX + padding, labelY + padding);
// Add point info to the list below
const pointContainer = document.createElement('div');
pointContainer.className = 'bounding-box-container';
const title = document.createElement('p');
title.style.color = color;
title.textContent = `Point: [${item.point.join(', ')}] - Label: ${label}`;
pointContainer.appendChild(title);
boundingBoxImages.appendChild(pointContainer);
});
// Draw axes and labels
ctx.strokeStyle = '#000000';
ctx.lineWidth = 1;
ctx.font = '26px Arial';
ctx.textAlign = 'right';
// Y-axis
ctx.beginPath();
ctx.moveTo(80, 20);
ctx.lineTo(80, image.height + 20);
ctx.stroke();
// Y-axis labels and ticks
for (let i = 0; i <= 1000; i += 100) {
const y = 20 + i / 1000 * image.height;
ctx.fillStyle = '#000000';
ctx.fillText(i.toString(), 75, y + 5);
ctx.beginPath();
ctx.moveTo(75, y);
ctx.lineTo(80, y);
ctx.stroke();
}
// X-axis
ctx.beginPath();
ctx.moveTo(80, image.height + 20);
ctx.lineTo(image.width + 80, image.height + 20);
ctx.stroke();
// X-axis labels and ticks
ctx.textAlign = 'center';
for (let i = 0; i <= 1000; i += 100) {
const x = 80 + i / 1000 * image.width;
ctx.fillStyle = '#000000';
ctx.fillText(i.toString(), x, image.height + 40);
ctx.beginPath();
ctx.moveTo(x, image.height + 20);
ctx.lineTo(x, image.height + 25);
ctx.stroke();
}
};
image.src = event.target.result;
};
reader.readAsDataURL(file);
}
function clearImage() {
document.getElementById('imageInput').value = '';
document.getElementById('canvas').getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('imagePreview').src = '';
document.getElementById('imagePreview').style.display = 'none';
document.getElementById('boundingBoxImages').innerHTML = '';
}
function previewImage(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById('imagePreview');
img.src = e.target.result;
img.style.display = 'block';
}
reader.readAsDataURL(file);
}
}
function handleModelChange() {
const modelSelect = document.getElementById('modelSelect');
const promptInput = document.getElementById('promptInput');
if (modelSelect.value === 'gemini-robotics-er-1.5-preview') {
promptInput.value = 'Point to no more than 10 items in the image. The label returned should be an identifying name for the object detected. The answer should follow the json format: [{"point": [y, x], "label": <label1>}, ...]. The points are in [y, x] format normalized to 0-1000.';
} else {
promptInput.value = 'Return bounding boxes as JSON arrays [ymin, xmin, ymax, xmax]\n';
}
}
function initializeFromURL() {
const urlParams = new URLSearchParams(window.location.search);
const modelParam = urlParams.get('model');
if (modelParam) {
const modelSelect = document.getElementById('modelSelect');
modelSelect.value = modelParam;
handleModelChange();
}
}
// Attach event listeners
document.getElementById('submitBtn').addEventListener('click', processImageAndPrompt);
document.getElementById('clearImageBtn').addEventListener('click', clearImage);
document.getElementById('imageInput').addEventListener('change', previewImage);
document.getElementById('modelSelect').addEventListener('change', handleModelChange);
// Initialize from URL parameters
initializeFromURL();
</script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
textarea {
width: 100%;
height: 100px;
}
#result, #imageContainer {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
#canvas {
max-width: 100%;
height: auto;
}
#imagePreview {
max-width: 100%;
display: none;
margin-top: 10px;
}
#boundingBoxImages {
margin-top: 20px;
}
#boundingBoxImages img {
max-width: 100%;
}
.bounding-box-container {
display: block;
margin-bottom: 20px;
}
.bounding-box-container p {
margin: 0 0 5px 0;
font-weight: bold;
}
.bounding-box-container img {
display: block;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<h1>Gemini API Image Bounding Box Visualization</h1>
<select id="modelSelect">
<option value="gemini-2.5-flash">gemini-2.5-flash (default)</option>
<option value="gemini-robotics-er-1.5-preview">gemini-robotics-er-1.5-preview</option>
<option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
<option value="gemini-2.5-pro">gemini-2.5-pro</option>
<option value="gemini-2.5-flash-lite-preview-06-17">gemini-2.5-flash-lite-preview-06-17</option>
<option value="gemini-2.5-flash-preview-04-17">gemini-2.5-flash-preview-04-17</option>
<option value="gemini-2.5-pro-exp-03-25">gemini-2.5-pro-exp-03-25</option>
<option value="gemini-2.5-pro-preview-03-25">gemini-2.5-pro-preview-03-25</option>
<option value="gemini-2.0-flash-lite">gemini-2.0-flash-lite</option>
<option value="gemini-2.0-pro-exp-02-05">gemini-2.0-pro-exp-02-05</option>
<option value="gemini-2.0-flash">gemini-2.0-flash</option>
<option value="gemini-2.0-flash-thinking-exp-01-21">gemini-2.0-flash-thinking-exp-01-21</option>
<option value="gemini-2.0-flash-thinking-exp-1219">gemini-2.0-flash-thinking-exp-1219</option>
<option value="gemini-2.0-flash-exp">gemini-2.0-flash-exp</option>
<option value="gemini-exp-1206">gemini-exp-1206</option>
<option value="gemini-exp-1121">gemini-exp-1121</option>
<option value="gemini-exp-1114">gemini-exp-1114</option>
<option value="gemini-1.5-flash-8b-001">gemini-1.5-flash-8b-001</option>
<option value="gemini-1.5-flash-8b-latest">gemini-1.5-flash-8b-latest</option>
<option value="gemini-1.5-flash-002">gemini-1.5-flash-002</option>
<option value="gemini-1.5-pro-002">gemini-1.5-pro-002</option>
<option value="gemini-1.5-flash-001">gemini-1.5-flash-001</option>
<option value="gemini-1.5-pro-001">gemini-1.5-pro-001</option>
<option value="gemini-1.5-flash-latest">gemini-1.5-flash-latest</option>
<option value="gemini-1.5-pro-latest">gemini-1.5-pro-latest</option>
<option value="gemini-pro">gemini-pro</option>
</select>
<input type="file" id="imageInput" accept="image/*">
<button id="clearImageBtn">Clear Image</button>
<textarea id="promptInput">Return bounding boxes as JSON arrays [ymin, xmin, ymax, xmax]
</textarea>
<button id="submitBtn">Process</button>
<div id="result"></div>
<div id="imageContainer">
<img id="imagePreview" alt="Image preview" />
<canvas id="canvas"></canvas>
</div>
<div id="boundingBoxImages"></div>
</body>
</html>