Running Pigo in Python example

This commit is contained in:
Endre Simo
2019-02-02 14:02:10 +02:00
parent 721cec1e9b
commit 3ce4f3795c
6 changed files with 0 additions and 0 deletions

95
examples/python/demo.py Normal file
View File

@@ -0,0 +1,95 @@
from ctypes import *
import subprocess
import numpy
import os
import cv2
import time
os.system('go build -o pigo.so -buildmode=c-shared pigo.go')
pigo = cdll.LoadLibrary('./pigo.so')
os.system('rm pigo.so')
MAX_NDETS = 2048
# define class GoPixelSlice to map to:
# C type struct { void *data; GoInt len; GoInt cap; }
class GoPixelSlice(Structure):
_fields_ = [
("pixels", POINTER(c_ubyte)), ("len", c_longlong), ("cap", c_longlong),
]
def process_frame(pixs):
dets = numpy.zeros(3*MAX_NDETS, dtype=numpy.float32)
pixs = pixs.flatten()
pixels = cast((c_ubyte * len(pixs))(*pixs), POINTER(c_ubyte))
# call FindFaces
faces = GoPixelSlice(pixels, len(pixs), len(pixs))
pigo.FindFaces.argtypes = [GoPixelSlice]
pigo.FindFaces.restype = c_void_p
#pigo.FindFaces.restype = POINTER((c_longlong * 3) * MAX_NDETS)
#pigo.FindFaces.restype = numpy.ctypeslib.ndpointer(dtype = c_longlong, shape = (MAX_NDETS, 3, ))
ndets = pigo.FindFaces(faces)
data_pointer = cast(ndets, POINTER((c_longlong * 3) * MAX_NDETS))
if data_pointer :
#print(data_pointer.contents)
#addr = addressof(data_pointer.contents)
#new_array = cast(addr, POINTER((c_longlong * 3) * MAX_NDETS)).contents
new_array = ((c_longlong * 3) * MAX_NDETS).from_address(addressof(data_pointer.contents))
# new_array = numpy.ctypeslib.as_array(data_pointer,shape=(8192,))
# buffer = numpy.core.multiarray.int_asbuffer(addressof(new_array), 3*MAX_NDETS)
# a = numpy.frombuffer(buffer, int)
# print(a)
res = numpy.ndarray(buffer=new_array, dtype=c_longlong, shape=(MAX_NDETS, 3,))
dets_len = res[0][0]
print(dets_len)
res = numpy.delete(res, 0, 0)
#print(res)
dets = numpy.frombuffer(data_pointer.contents, dtype=numpy.dtype(int))
dets = numpy.trim_zeros(dets)
#dets = dets.astype(int)
#print(dets)
dets = list(res.reshape(-1, 3))[0:dets_len]
return dets
#print(dets)
#print(dets)
#return list(dets.reshape(-1, 4))[0:dets]
#res = pigo.FindFaces(pixels, gray.shape[0], gray.shape[1], cascade)
#print(res.dets)
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
w = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
h = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
print (w,h)
while(True):
ret, frame = cap.read()
pixs = numpy.ascontiguousarray(frame[:, :, 1].reshape((frame.shape[0], frame.shape[1])))
if not numpy.any(pixs):
continue
dets = process_frame(pixs) # pixs needs to be numpy.uint8 array
print(dets)
if dets is not None:
for det in dets:
cv2.circle(frame, (int(det[1]), int(det[0])), int(det[2]/2.0), (0, 0, 255), 2)
cv2.imshow('', frame)
if cv2.waitKey(5) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

119
examples/python/pigo.go Normal file
View File

@@ -0,0 +1,119 @@
package main
import "C"
import (
"fmt"
"io/ioutil"
"log"
"reflect"
"runtime"
"unsafe"
"github.com/esimov/pigo/core"
)
var (
cascade []byte
err error
p *pigo.Pigo
classifier *pigo.Pigo
)
func main() {}
//export FindFaces
func FindFaces(pixels []uint8) uintptr {
dets := clusterDetection(pixels, 480, 640)
result := make([][]int, len(dets))
for i := 0; i < len(dets); i++ {
if dets[i].Q >= 5.0 {
result[i] = append(result[i], dets[i].Row, dets[i].Col, dets[i].Scale)
}
}
//fmt.Println(dets)
fmt.Println(result)
if len(result) > 0 {
det := make([]int, 0, len(result))
for _, v := range result {
det = append(det, v...)
}
det = append([]int{len(result), 0, 0}, det...)
fmt.Println(det)
s := *(*[]int)(unsafe.Pointer(&det))
p := uintptr(unsafe.Pointer(&s[0]))
return p
sh := &reflect.SliceHeader{
Data: p,
Len: len(result),
Cap: len(result),
}
data := *(*[][]int)(unsafe.Pointer(sh))
fmt.Println(data)
runtime.KeepAlive(result)
return uintptr(unsafe.Pointer(&data[0]))
}
return 0
}
func clusterDetection(pixels []uint8, rows, cols int) []pigo.Detection {
// cfp := *(*[]byte)(unsafe.Pointer(&cascadeFile))
// p := uintptr(unsafe.Pointer(&cfp[0]))
// size := len(cascadeFile)
// var data []byte
// sh := (*reflect.SliceHeader)(unsafe.Pointer(&data))
// sh.Data = p
// sh.Len = size
// sh.Cap = size
// fmt.Println(cascadeFile)
// fmt.Println(data)
// fmt.Println(uintptr(unsafe.Pointer(&cfp[0])))
fmt.Println("P:", len(pixels))
fmt.Println("DIM:", rows, cols)
cParams := pigo.CascadeParams{
MinSize: 20,
MaxSize: 1000,
ShiftFactor: 0.22,
ScaleFactor: 1.1,
ImageParams: pigo.ImageParams{
Pixels: pixels,
Rows: rows,
Cols: cols,
Dim: cols,
},
}
if len(cascade) == 0 {
cascade, err = ioutil.ReadFile("../../data/facefinder")
if err != nil {
log.Fatalf("Error reading the cascade file: %v", err)
}
// Unpack the binary file. This will return the number of cascade trees,
// the tree depth, the threshold and the prediction from tree's leaf nodes.
classifier, err = p.Unpack(cascade)
if err != nil {
log.Fatalf("Error reading the cascade file: %s", err)
}
}
// Run the classifier over the obtained leaf nodes and return the detection results.
// The result contains quadruplets representing the row, column, scale and detection score.
dets := classifier.RunCascade(cParams, 0.0)
// Calculate the intersection over union (IoU) of two clusters.
dets = classifier.ClusterDetections(dets, 0)
return dets
}

72
examples/python/pigo.h Normal file
View File

@@ -0,0 +1,72 @@
/* Created by "go tool cgo" - DO NOT EDIT. */
/* package command-line-arguments */
#line 1 "cgo-builtin-prolog"
#include <stddef.h> /* for ptrdiff_t below */
#ifndef GO_CGO_EXPORT_PROLOGUE_H
#define GO_CGO_EXPORT_PROLOGUE_H
typedef struct { const char *p; ptrdiff_t n; } _GoString_;
#endif
/* Start of preamble from import "C" comments. */
/* End of preamble from import "C" comments. */
/* Start of boilerplate cgo prologue. */
#line 1 "cgo-gcc-export-header-prolog"
#ifndef GO_CGO_PROLOGUE_H
#define GO_CGO_PROLOGUE_H
typedef signed char GoInt8;
typedef unsigned char GoUint8;
typedef short GoInt16;
typedef unsigned short GoUint16;
typedef int GoInt32;
typedef unsigned int GoUint32;
typedef long long GoInt64;
typedef unsigned long long GoUint64;
typedef GoInt64 GoInt;
typedef GoUint64 GoUint;
typedef __SIZE_TYPE__ GoUintptr;
typedef float GoFloat32;
typedef double GoFloat64;
typedef float _Complex GoComplex64;
typedef double _Complex GoComplex128;
/*
static assertion to make sure the file is being used on architecture
at least with matching size of GoInt.
*/
typedef char _check_for_64_bit_pointer_matching_GoInt[sizeof(void*)==64/8 ? 1:-1];
typedef _GoString_ GoString;
typedef void *GoMap;
typedef void *GoChan;
typedef struct { void *t; void *v; } GoInterface;
typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
#endif
/* End of boilerplate cgo prologue. */
#ifdef __cplusplus
extern "C" {
#endif
extern GoUintptr FindFaces(GoSlice p0);
#ifdef __cplusplus
}
#endif