Skip to content
This repository was archived by the owner on Jul 1, 2024. It is now read-only.

Commit 147a7d8

Browse files
Update tsconfig
1 parent 24fa90a commit 147a7d8

10 files changed

+394
-71
lines changed

darknet.d.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ export declare class DarknetBase {
99
* @param config
1010
*/
1111
constructor(config: IDarknetConfig);
12-
private getArrayFromBuffer(buffer, length, type);
13-
private bufferToDetections(buffer, length);
14-
private _detectSync(net, meta, image, thresh?, hier_thresh?, nms?);
12+
private getArrayFromBuffer;
13+
private bufferToDetections;
14+
private _detectSync;
1515
protected _detectAsync(net: any, meta: any, image: any, thresh?: number, hier_thresh?: number, nms?: number): Promise<Detection[]>;
1616
/**
1717
* Synchronously detect objects in an image.
@@ -37,7 +37,7 @@ export declare class DarknetBase {
3737
* @returns {Buffer}
3838
*/
3939
imageToRGBBuffer(image: any): Buffer;
40-
private rgbToDarknet(buffer, w, h, c);
40+
private rgbToDarknet;
4141
/**
4242
* Transform an RGB buffer to a darknet encoded image
4343
* @param buffer - rgb buffer

darknet.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
1414
function step(op) {
1515
if (f) throw new TypeError("Generator is already executing.");
1616
while (_) try {
17-
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
18-
if (y = 0, t) op = [0, t.value];
17+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18+
if (y = 0, t) op = [op[0] & 2, t.value];
1919
switch (op[0]) {
2020
case 0: case 1: t = op; break;
2121
case 4: _.label++; return { value: op[1], done: false };
@@ -151,8 +151,8 @@ var DarknetBase = /** @class */ (function () {
151151
};
152152
DarknetBase.prototype._detectAsync = function (net, meta, image, thresh, hier_thresh, nms) {
153153
return __awaiter(this, void 0, void 0, function () {
154-
var _this = this;
155154
var pnum, dets, num, detections;
155+
var _this = this;
156156
return __generator(this, function (_a) {
157157
switch (_a.label) {
158158
case 0: return [4 /*yield*/, new Promise(function (res, rej) {
@@ -283,8 +283,8 @@ var DarknetBase = /** @class */ (function () {
283283
*/
284284
DarknetBase.prototype.RGBBufferToImageAsync = function (buffer, w, h, c) {
285285
return __awaiter(this, void 0, void 0, function () {
286-
var _this = this;
287286
var floatBuff;
287+
var _this = this;
288288
return __generator(this, function (_a) {
289289
floatBuff = this.rgbToDarknet(buffer, w, h, c);
290290
return [2 /*return*/, new Promise(function (res, rej) { return _this.darknet.float_to_image.async(w, h, c, new Uint8Array(floatBuff.buffer, 0, floatBuff.length * Float32Array.BYTES_PER_ELEMENT), function (e, image) { return e ? rej(e) : res(image); }); })];
@@ -299,8 +299,8 @@ var DarknetBase = /** @class */ (function () {
299299
*/
300300
DarknetBase.prototype.detectAsync = function (image, config) {
301301
return __awaiter(this, void 0, void 0, function () {
302-
var _this = this;
303302
var thresh, hier_thresh, nms, darkNetLoadedImage, imageData, _a, detection;
303+
var _this = this;
304304
return __generator(this, function (_b) {
305305
switch (_b.label) {
306306
case 0:

detector.d.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export declare class Darknet extends DarknetBase {
44
private completion$;
55
private detection$;
66
constructor(config: IDarknetConfig);
7-
private doAsyncDetection(image, config?);
8-
private subscribeToDetections();
7+
private doAsyncDetection;
8+
private subscribeToDetections;
99
detectAsync(image: string | IBufferImage, options?: IConfig): Promise<Detection[]>;
1010
}

detector.js

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
"use strict";
22
var __extends = (this && this.__extends) || (function () {
3-
var extendStatics = Object.setPrototypeOf ||
4-
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5-
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
3+
var extendStatics = function (d, b) {
4+
extendStatics = Object.setPrototypeOf ||
5+
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6+
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7+
return extendStatics(d, b);
8+
};
69
return function (d, b) {
710
extendStatics(d, b);
811
function __() { this.constructor = d; }
@@ -24,8 +27,8 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
2427
function step(op) {
2528
if (f) throw new TypeError("Generator is already executing.");
2629
while (_) try {
27-
if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
28-
if (y = 0, t) op = [0, t.value];
30+
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
31+
if (y = 0, t) op = [op[0] & 2, t.value];
2932
switch (op[0]) {
3033
case 0: case 1: t = op; break;
3134
case 4: _.label++; return { value: op[1], done: false };
@@ -62,8 +65,8 @@ var Darknet = /** @class */ (function (_super) {
6265
}
6366
Darknet.prototype.doAsyncDetection = function (image, config) {
6467
return __awaiter(this, void 0, void 0, function () {
65-
var _this = this;
6668
var thresh, hier_thresh, nms, darkNetLoadedImage, imageData, _a, detection;
69+
var _this = this;
6770
return __generator(this, function (_b) {
6871
switch (_b.label) {
6972
case 0:

lib/darknet.js

Lines changed: 280 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,280 @@
1+
var _this = this;
2+
var ffi = require('ffi');
3+
var ref = require('ref');
4+
var Struct = require('ref-struct');
5+
var fs_1 = require('fs');
6+
var char_pointer = ref.refType('char');
7+
var float_pointer = ref.refType('float');
8+
var int_pointer = ref.refType('int');
9+
var BBOX = Struct({
10+
'x': 'float',
11+
'y': 'float',
12+
'w': 'float',
13+
'h': 'float'
14+
});
15+
var DETECTION = Struct({
16+
'bbox': BBOX,
17+
'classes': 'int',
18+
'prob': float_pointer,
19+
'mask': float_pointer,
20+
'objectness': 'float',
21+
'sort_class': 'int'
22+
});
23+
var IMAGE = Struct({
24+
'w': 'int',
25+
'h': 'int',
26+
'c': 'int',
27+
'data': float_pointer
28+
});
29+
var METADATA = Struct({
30+
'classes': 'int',
31+
'names': 'string'
32+
});
33+
var detection_pointer = ref.refType(DETECTION);
34+
var library = __dirname + "/libdarknet";
35+
var DarknetBase = (function () {
36+
/**
37+
* A new instance of pjreddie's darknet. Create an instance as soon as possible in your app, because it takes a while to init.
38+
* @param config
39+
*/
40+
function DarknetBase(config) {
41+
this.async = _detectAsync(net, any, meta, any, image, any, thresh ? : number, hier_thresh ? : number, nms ? : number);
42+
if (!config)
43+
throw new Error("A config file is required");
44+
if (!config.names && !config.namefile)
45+
throw new Error("Config must include detection class names");
46+
if (!config.names && config.namefile)
47+
config.names = fs_1.readFileSync(config.namefile, 'utf8').split('\n');
48+
if (!config.names)
49+
throw new Error("No names detected.");
50+
if (!config.config)
51+
throw new Error("Config must include location to yolo config file");
52+
if (!config.weights)
53+
throw new Error("config must include the path to trained weights");
54+
this.names = config.names.filter(function (a) { return a.split("").length > 0; });
55+
this.meta = new METADATA;
56+
this.meta.classes = this.names.length;
57+
this.meta.names = this.names.join('\n');
58+
this.darknet = ffi.Library(library, {
59+
'float_to_image': [IMAGE, ['int', 'int', 'int', float_pointer]],
60+
'load_image_color': [IMAGE, ['string', 'int', 'int']],
61+
'network_predict_image': [float_pointer, ['pointer', IMAGE]],
62+
'get_network_boxes': [detection_pointer, ['pointer', 'int', 'int', 'float', 'float', int_pointer, 'int', int_pointer]],
63+
'do_nms_obj': ['void', [detection_pointer, 'int', 'int', 'float']],
64+
'free_image': ['void', [IMAGE]],
65+
'free_detections': ['void', [detection_pointer, 'int']],
66+
'load_network': ['pointer', ['string', 'string', 'int']],
67+
'get_metadata': [METADATA, ['string']],
68+
});
69+
this.net = this.darknet.load_network(config.config, config.weights, 0);
70+
}
71+
DarknetBase.prototype.getArrayFromBuffer = function (buffer, length, type) {
72+
var array = [];
73+
for (var i = 0; i < length; i++) {
74+
array.push(ref.get(ref.reinterpret(buffer, type.size, i * type.size), 0, type));
75+
}
76+
return array;
77+
};
78+
DarknetBase.prototype.bufferToDetections = function (buffer, length) {
79+
var detections = [];
80+
for (var i = 0; i < length; i++) {
81+
var det = ref.get(ref.reinterpret(buffer, 48, i * DETECTION.size), 0, DETECTION);
82+
var prob = this.getArrayFromBuffer(det.prob, this.meta.classes, ref.types.float);
83+
for (var j = 0; j < this.meta.classes; j++) {
84+
if (prob[j] > 0) {
85+
var b = det.bbox;
86+
detections.push({
87+
name: this.names[j],
88+
prob: prob[j],
89+
box: {
90+
x: b.x,
91+
y: b.y,
92+
w: b.w,
93+
h: b.h
94+
}
95+
});
96+
}
97+
}
98+
}
99+
return detections;
100+
};
101+
DarknetBase.prototype._detectSync = function (net, meta, image, thresh, hier_thresh, nms) {
102+
if (!thresh)
103+
thresh = 0.5;
104+
if (!hier_thresh)
105+
hier_thresh = 0.5;
106+
if (!nms)
107+
nms = 0.45;
108+
this.darknet.network_predict_image(net, image);
109+
var pnum = ref.alloc('int');
110+
var dets = this.darknet.get_network_boxes(net, image.w, image.h, thresh, hier_thresh, ref.NULL_POINTER, 0, pnum);
111+
var num = (pnum), as = any, deref = ();
112+
this.darknet.do_nms_obj(dets, num, meta.classes, nms);
113+
var detections = this.bufferToDetections(dets, num);
114+
this.darknet.free_detections(dets, num);
115+
return detections;
116+
};
117+
DarknetBase.prototype.Promise = ;
118+
return DarknetBase;
119+
})();
120+
exports.DarknetBase = DarknetBase;
121+
> {
122+
await: new Promise(function (res, rej) {
123+
return _this.darknet.network_predict_image.async(net, image, function (e) { return e ? rej(e) : res(); });
124+
}),
125+
let: pnum = ref.alloc('int'),
126+
const: dets = await, new: Promise(function (res, rej) {
127+
return _this.darknet.get_network_boxes.async(net, image.w, image.h, thresh, hier_thresh, ref.NULL_POINTER, 0, pnum, function (err, dets) { return err ? rej(err) : res(dets); });
128+
}),
129+
const: num = (pnum), as: any, deref: function () { },
130+
await: new Promise(function (res, rej) {
131+
return _this.darknet.do_nms_obj.async(dets, num, meta.classes, nms, function (e) { return e ? rej(e) : res(); });
132+
}),
133+
const: detections = this.bufferToDetections(dets, num),
134+
this: .darknet.free_detections(dets, num),
135+
return: detections
136+
};
137+
/**
138+
* Synchronously detect objects in an image.
139+
* @param image the destination of the image to be detected
140+
* @param config optional configuration (threshold, etc.)
141+
*/
142+
detect(image, string | IBufferImage, config ? : IConfig);
143+
{
144+
if (!config)
145+
config = {};
146+
var darkNetLoadedImage_1 = typeof image === 'string';
147+
var imageData_1 = typeof image === 'string' ?
148+
this.getImageFromPath(image) :
149+
this.RGBBufferToImage(image.b, image.w, image.h, image.c);
150+
var detection_1 = this._detectSync(this.net, this.meta, imageData_1, config.thresh, config.hier_thresh, config.nms);
151+
if (darkNetLoadedImage_1) {
152+
// memory is owned by the darknet lib
153+
this.darknet.free_image(imageData_1);
154+
}
155+
else {
156+
}
157+
return detection_1;
158+
}
159+
/**
160+
* Get a Darknet Image from path
161+
* @param path
162+
* @returns IMAGE
163+
*/
164+
getImageFromPath(path, string);
165+
{
166+
return this.darknet.load_image_color(path, 0, 0);
167+
}
168+
/**
169+
* Get a Darknet Image async from path
170+
* @param path
171+
* @returns Promise<IMAGE>
172+
*/
173+
async;
174+
getImageFromPathAsync(path, String);
175+
{
176+
return new Promise(function (res, rej) {
177+
return _this.darknet.load_image_color.async(path, 0, 0, function (e, image) { return e ? rej(e) : res(image); });
178+
});
179+
}
180+
/**
181+
* convert darknet image to rgb buffer
182+
* @param {IMAGE} image
183+
* @returns {Buffer}
184+
*/
185+
imageToRGBBuffer(image, any);
186+
{
187+
var w = image.w;
188+
var h = image.h;
189+
var c = image.c;
190+
var imageElements = w * h * c;
191+
var imageData_2 = new Float32Array(image.data.reinterpret(imageElements * Float32Array.BYTES_PER_ELEMENT, 0).buffer, 0, imageElements);
192+
var rgbBuffer = Buffer.allocUnsafe(imageData_2.length);
193+
var step = c * w;
194+
var i, k, j;
195+
for (i = 0; i < h; ++i) {
196+
for (k = 0; k < c; ++k) {
197+
for (j = 0; j < w; ++j) {
198+
rgbBuffer[i * step + j * c + k] = imageData_2[k * w * h + i * w + j] * 255;
199+
}
200+
}
201+
}
202+
return rgbBuffer;
203+
}
204+
rgbToDarknet(buffer, Buffer, w, number, h, number, c, number);
205+
Float32Array;
206+
{
207+
var imageElements = w * h * c;
208+
var floatBuff = new Float32Array(imageElements);
209+
var step = w * c;
210+
var i, k, j;
211+
for (i = 0; i < h; ++i) {
212+
for (k = 0; k < c; ++k) {
213+
for (j = 0; j < w; ++j) {
214+
floatBuff[k * w * h + i * w + j] = buffer[i * step + j * c + k] / 255;
215+
}
216+
}
217+
}
218+
return floatBuff;
219+
}
220+
/**
221+
* Transform an RGB buffer to a darknet encoded image
222+
* @param buffer - rgb buffer
223+
* @param w - width
224+
* @param h - height
225+
* @param c - channels
226+
* @returns {IMAGE}
227+
*/
228+
RGBBufferToImage(buffer, Buffer, w, number, h, number, c, number);
229+
{
230+
var floatBuff = this.rgbToDarknet(buffer, w, h, c);
231+
return this.darknet.float_to_image(w, h, c, new Uint8Array(floatBuff.buffer, 0, floatBuff.length * Float32Array.BYTES_PER_ELEMENT));
232+
}
233+
/**
234+
* Transform an RGB buffer to a darknet encoded image
235+
* @param buffer - rgb buffer
236+
* @param w - width
237+
* @param h - height
238+
* @param c - channels
239+
* @returns {Promise<IMAGE>}
240+
*/
241+
async;
242+
RGBBufferToImageAsync(buffer, Buffer, w, number, h, number, c, number);
243+
Promise < any > {
244+
const: floatBuff = this.rgbToDarknet(buffer, w, h, c),
245+
return: new Promise(function (res, rej) { return _this.darknet.float_to_image.async(w, h, c, new Uint8Array(floatBuff.buffer, 0, floatBuff.length * Float32Array.BYTES_PER_ELEMENT), function (e, image) { return e ? rej(e) : res(image); }); })
246+
};
247+
/**
248+
* Asynchronously detect objects in an image.
249+
* @param image
250+
* @param config
251+
* @returns A promise
252+
*/
253+
async;
254+
detectAsync(image, string | IBufferImage, config ? : IConfig);
255+
Promise < Detection[] > {
256+
if: function () { } };
257+
!config;
258+
config = {};
259+
var thresh = (config.thresh) ? config.thresh : 0.5;
260+
var hier_thresh = (config.hier_thresh) ? config.hier_thresh : 0.5;
261+
var nms = (config.nms) ? config.nms : 0.5;
262+
var darkNetLoadedImage = typeof image === 'string';
263+
var imageData = typeof image === 'string' ?
264+
await : this.getImageFromPathAsync(image), await = this.RGBBufferToImageAsync(image.b, image.w, image.h, image.c);
265+
var detection = await;
266+
this._detectAsync(this.net, this.meta, imageData, thresh, hier_thresh, nms);
267+
if (darkNetLoadedImage) {
268+
// memory is owned by the darknet lib
269+
await;
270+
new Promise(function (res, rej) {
271+
return _this.darknet.free_image.async(imageData, function (e) { return e ? rej(e) : res(); });
272+
});
273+
}
274+
else {
275+
}
276+
return detection;
277+
var detector_1 = require('./detector');
278+
exports.Darknet = detector_1.Darknet;
279+
var detector_2 = require('./detector');
280+
exports.DarknetExperimental = detector_2.Darknet;

0 commit comments

Comments
 (0)