Commit f36f8067 authored by Roman Donchenko's avatar Roman Donchenko

Merge remote-tracking branch 'origin/2.4' into merge-2.4

Conflicts:
	modules/calib3d/include/opencv2/calib3d/calib3d.hpp
	modules/core/include/opencv2/core/core.hpp
	modules/core/include/opencv2/core/cuda/limits.hpp
	modules/core/include/opencv2/core/internal.hpp
	modules/core/src/matrix.cpp
	modules/nonfree/test/test_features2d.cpp
	modules/ocl/include/opencv2/ocl/ocl.hpp
	modules/ocl/src/hog.cpp
	modules/ocl/test/test_haar.cpp
	modules/ocl/test/test_objdetect.cpp
	modules/ocl/test/test_pyrup.cpp
	modules/ts/src/precomp.hpp
	samples/ocl/facedetect.cpp
	samples/ocl/hog.cpp
	samples/ocl/pyrlk_optical_flow.cpp
	samples/ocl/surf_matcher.cpp
parents eff6dccb 3bab7391
No related merge requests found
......@@ -44,7 +44,7 @@ if(OPENCL_FOUND)
set(OPENCL_INCLUDE_DIRS ${OPENCL_INCLUDE_DIR})
set(OPENCL_LIBRARIES ${OPENCL_LIBRARY})
if(WIN64)
if(WIN32 AND X86_64)
set(CLAMD_POSSIBLE_LIB_SUFFIXES lib64/import)
elseif(WIN32)
set(CLAMD_POSSIBLE_LIB_SUFFIXES lib32/import)
......
......@@ -278,8 +278,8 @@ CV_EXPORTS int recoverPose( InputArray E, InputArray points1, InputArray points2
//! finds coordinates of epipolar lines corresponding the specified points
CV_EXPORTS void computeCorrespondEpilines( InputArray points, int whichImage,
InputArray F, OutputArray lines );
CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage,
InputArray F, OutputArray lines );
CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2,
InputArray projPoints1, InputArray projPoints2,
......
......@@ -78,7 +78,8 @@ public:
EXPR = 6 << KIND_SHIFT,
OPENGL_BUFFER = 7 << KIND_SHIFT,
CUDA_MEM = 8 << KIND_SHIFT,
GPU_MAT = 9 << KIND_SHIFT
GPU_MAT = 9 << KIND_SHIFT,
OCL_MAT =10 << KIND_SHIFT
};
_InputArray();
......
......@@ -71,6 +71,30 @@
# endif
#endif
#ifdef _OPENMP
# define HAVE_OPENMP
#endif
#ifdef __APPLE__
# define HAVE_GCD
#endif
#if defined _MSC_VER && _MSC_VER >= 1600
# define HAVE_CONCURRENCY
#endif
#if defined HAVE_TBB
# define CV_PARALLEL_FRAMEWORK "tbb"
#elif defined HAVE_CSTRIPES
# define CV_PARALLEL_FRAMEWORK "cstripes"
#elif defined HAVE_OPENMP
# define CV_PARALLEL_FRAMEWORK "openmp"
#elif defined HAVE_GCD
# define CV_PARALLEL_FRAMEWORK "gcd"
#elif defined HAVE_CONCURRENCY
# define CV_PARALLEL_FRAMEWORK "ms-concurrency"
#endif
namespace cv
{
#ifdef HAVE_TBB
......
......@@ -995,6 +995,11 @@ Mat _InputArray::getMat(int i) const
return !v.empty() ? Mat(size(i), t, (void*)&v[0]) : Mat();
}
if( k == OCL_MAT )
{
CV_Error(CV_StsNotImplemented, "This method is not implemented for oclMat yet");
}
if( k == STD_VECTOR_MAT )
{
const std::vector<Mat>& v = *(const std::vector<Mat>*)obj;
......@@ -1100,6 +1105,11 @@ void _InputArray::getMatVector(std::vector<Mat>& mv) const
return;
}
if( k == OCL_MAT )
{
CV_Error(CV_StsNotImplemented, "This method is not implemented for oclMat yet");
}
CV_Assert( k == STD_VECTOR_MAT );
//if( k == STD_VECTOR_MAT )
{
......@@ -1224,6 +1234,11 @@ Size _InputArray::size(int i) const
return d_mat->size();
}
if( k == OCL_MAT )
{
CV_Error(CV_StsNotImplemented, "This method is not implemented for oclMat yet");
}
CV_Assert( k == CUDA_MEM );
//if( k == CUDA_MEM )
{
......@@ -1338,6 +1353,11 @@ bool _InputArray::empty() const
if( k == OPENGL_BUFFER )
return ((const ogl::Buffer*)obj)->empty();
if( k == OCL_MAT )
{
CV_Error(CV_StsNotImplemented, "This method is not implemented for oclMat yet");
}
if( k == GPU_MAT )
return ((const gpu::GpuMat*)obj)->empty();
......@@ -1573,6 +1593,11 @@ void _OutputArray::create(int dims, const int* sizes, int mtype, int i, bool all
return;
}
if( k == OCL_MAT )
{
CV_Error(CV_StsNotImplemented, "This method is not implemented for oclMat yet");
}
if( k == NONE )
{
CV_Error(CV_StsNullPtr, "create() called for the missing output array" );
......@@ -1684,6 +1709,11 @@ void _OutputArray::release() const
return;
}
if( k == OCL_MAT )
{
CV_Error(CV_StsNotImplemented, "This method is not implemented for oclMat yet");
}
CV_Assert( k == STD_VECTOR_MAT );
//if( k == STD_VECTOR_MAT )
{
......
......@@ -61,17 +61,6 @@
#endif
#endif
#ifdef _OPENMP
#define HAVE_OPENMP
#endif
#ifdef __APPLE__
#define HAVE_GCD
#endif
#if defined _MSC_VER && _MSC_VER >= 1600
#define HAVE_CONCURRENCY
#endif
/* IMPORTANT: always use the same order of defines
1. HAVE_TBB - 3rdparty library, should be explicitly enabled
......@@ -110,10 +99,6 @@
#endif
#endif
#if defined HAVE_TBB || defined HAVE_CSTRIPES || defined HAVE_OPENMP || defined HAVE_GCD || defined HAVE_CONCURRENCY
#define HAVE_PARALLEL_FRAMEWORK
#endif
namespace cv
{
ParallelLoopBody::~ParallelLoopBody() {}
......@@ -121,7 +106,7 @@ namespace cv
namespace
{
#ifdef HAVE_PARALLEL_FRAMEWORK
#ifdef CV_PARALLEL_FRAMEWORK
class ParallelLoopBodyWrapper
{
public:
......@@ -218,7 +203,7 @@ public:
static SchedPtr pplScheduler;
#endif
#endif // HAVE_PARALLEL_FRAMEWORK
#endif // CV_PARALLEL_FRAMEWORK
} //namespace
......@@ -226,7 +211,7 @@ static SchedPtr pplScheduler;
void cv::parallel_for_(const cv::Range& range, const cv::ParallelLoopBody& body, double nstripes)
{
#ifdef HAVE_PARALLEL_FRAMEWORK
#ifdef CV_PARALLEL_FRAMEWORK
if(numThreads != 0)
{
......@@ -281,7 +266,7 @@ void cv::parallel_for_(const cv::Range& range, const cv::ParallelLoopBody& body,
}
else
#endif // HAVE_PARALLEL_FRAMEWORK
#endif // CV_PARALLEL_FRAMEWORK
{
(void)nstripes;
body(range);
......@@ -290,7 +275,7 @@ void cv::parallel_for_(const cv::Range& range, const cv::ParallelLoopBody& body,
int cv::getNumThreads(void)
{
#ifdef HAVE_PARALLEL_FRAMEWORK
#ifdef CV_PARALLEL_FRAMEWORK
if(numThreads == 0)
return 1;
......@@ -333,7 +318,7 @@ int cv::getNumThreads(void)
void cv::setNumThreads( int threads )
{
(void)threads;
#ifdef HAVE_PARALLEL_FRAMEWORK
#ifdef CV_PARALLEL_FRAMEWORK
numThreads = threads;
#endif
......
......@@ -126,7 +126,7 @@ typedef int Ncv32s;
typedef unsigned int Ncv32u;
typedef short Ncv16s;
typedef unsigned short Ncv16u;
typedef char Ncv8s;
typedef signed char Ncv8s;
typedef unsigned char Ncv8u;
typedef float Ncv32f;
typedef double Ncv64f;
......
......@@ -51,7 +51,7 @@ template<typename TBase> inline __host__ __device__ TBase _pixMaxVal();
template<> static inline __host__ __device__ Ncv8u _pixMaxVal<Ncv8u>() {return UCHAR_MAX;}
template<> static inline __host__ __device__ Ncv16u _pixMaxVal<Ncv16u>() {return USHRT_MAX;}
template<> static inline __host__ __device__ Ncv32u _pixMaxVal<Ncv32u>() {return UINT_MAX;}
template<> static inline __host__ __device__ Ncv8s _pixMaxVal<Ncv8s>() {return CHAR_MAX;}
template<> static inline __host__ __device__ Ncv8s _pixMaxVal<Ncv8s>() {return SCHAR_MAX;}
template<> static inline __host__ __device__ Ncv16s _pixMaxVal<Ncv16s>() {return SHRT_MAX;}
template<> static inline __host__ __device__ Ncv32s _pixMaxVal<Ncv32s>() {return INT_MAX;}
template<> static inline __host__ __device__ Ncv32f _pixMaxVal<Ncv32f>() {return FLT_MAX;}
......@@ -61,7 +61,7 @@ template<typename TBase> inline __host__ __device__ TBase _pixMinVal();
template<> static inline __host__ __device__ Ncv8u _pixMinVal<Ncv8u>() {return 0;}
template<> static inline __host__ __device__ Ncv16u _pixMinVal<Ncv16u>() {return 0;}
template<> static inline __host__ __device__ Ncv32u _pixMinVal<Ncv32u>() {return 0;}
template<> static inline __host__ __device__ Ncv8s _pixMinVal<Ncv8s>() {return CHAR_MIN;}
template<> static inline __host__ __device__ Ncv8s _pixMinVal<Ncv8s>() {return SCHAR_MIN;}
template<> static inline __host__ __device__ Ncv16s _pixMinVal<Ncv16s>() {return SHRT_MIN;}
template<> static inline __host__ __device__ Ncv32s _pixMinVal<Ncv32s>() {return INT_MIN;}
template<> static inline __host__ __device__ Ncv32f _pixMinVal<Ncv32f>() {return FLT_MIN;}
......
/*
* cap_ios.h
* For iOS video I/O
/* For iOS video I/O
* by Eduard Feicho on 29/07/12
* Copyright 2012. All rights reserved.
*
......@@ -90,6 +88,12 @@
- (void)createVideoPreviewLayer;
- (void)updateOrientation;
- (void)lockFocus;
- (void)unlockFocus;
- (void)lockExposure;
- (void)unlockExposure;
- (void)lockBalance;
- (void)unlockBalance;
@end
......@@ -116,6 +120,7 @@
BOOL grayscaleMode;
BOOL recordVideo;
BOOL rotateVideo;
AVAssetWriterInput* recordAssetWriterInput;
AVAssetWriterInputPixelBufferAdaptor* recordPixelBufferAdaptor;
AVAssetWriter* recordAssetWriter;
......@@ -128,6 +133,7 @@
@property (nonatomic, assign) BOOL grayscaleMode;
@property (nonatomic, assign) BOOL recordVideo;
@property (nonatomic, assign) BOOL rotateVideo;
@property (nonatomic, retain) AVAssetWriterInput* recordAssetWriterInput;
@property (nonatomic, retain) AVAssetWriterInputPixelBufferAdaptor* recordPixelBufferAdaptor;
@property (nonatomic, retain) AVAssetWriter* recordAssetWriter;
......
......@@ -2,6 +2,7 @@
* cap_ios_abstract_camera.mm
* For iOS video I/O
* by Eduard Feicho on 29/07/12
* by Alexander Shishkov on 17/07/13
* Copyright 2012. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
......@@ -405,4 +406,89 @@
}
}
- (void)lockFocus;
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device isFocusModeSupported:AVCaptureFocusModeLocked]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.focusMode = AVCaptureFocusModeLocked;
[device unlockForConfiguration];
} else {
NSLog(@"unable to lock device for locked focus configuration %@", [error localizedDescription]);
}
}
}
- (void) unlockFocus;
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
[device unlockForConfiguration];
} else {
NSLog(@"unable to lock device for autofocus configuration %@", [error localizedDescription]);
}
}
}
- (void)lockExposure;
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device isExposureModeSupported:AVCaptureExposureModeLocked]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.exposureMode = AVCaptureExposureModeLocked;
[device unlockForConfiguration];
} else {
NSLog(@"unable to lock device for locked exposure configuration %@", [error localizedDescription]);
}
}
}
- (void) unlockExposure;
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
[device unlockForConfiguration];
} else {
NSLog(@"unable to lock device for autoexposure configuration %@", [error localizedDescription]);
}
}
}
- (void)lockBalance;
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeLocked]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.whiteBalanceMode = AVCaptureWhiteBalanceModeLocked;
[device unlockForConfiguration];
} else {
NSLog(@"unable to lock device for locked white balance configuration %@", [error localizedDescription]);
}
}
}
- (void) unlockBalance;
{
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {
NSError *error = nil;
if ([device lockForConfiguration:&error]) {
device.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
[device unlockForConfiguration];
} else {
NSLog(@"unable to lock device for auto white balance configuration %@", [error localizedDescription]);
}
}
}
@end
......@@ -2,6 +2,7 @@
* cap_ios_video_camera.mm
* For iOS video I/O
* by Eduard Feicho on 29/07/12
* by Alexander Shishkov on 17/07/13
* Copyright 2012. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
......@@ -30,7 +31,6 @@
#import "opencv2/highgui/cap_ios.h"
#include "precomp.hpp"
#import <AssetsLibrary/AssetsLibrary.h>
......@@ -70,6 +70,7 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
@synthesize videoDataOutput;
@synthesize recordVideo;
@synthesize rotateVideo;
//@synthesize videoFileOutput;
@synthesize recordAssetWriterInput;
@synthesize recordPixelBufferAdaptor;
......@@ -85,6 +86,7 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
if (self) {
self.useAVCaptureVideoPreviewLayer = NO;
self.recordVideo = NO;
self.rotateVideo = NO;
}
return self;
}
......@@ -269,13 +271,8 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
}
#pragma mark - Private Interface
- (void)createVideoDataOutput;
{
// Make a video data output
......@@ -389,6 +386,38 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
[self.parentView.layer addSublayer:self.customPreviewLayer];
}
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
{
CGSize frameSize = CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image));
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], kCVPixelBufferCGImageCompatibilityKey,
[NSNumber numberWithBool:NO], kCVPixelBufferCGBitmapContextCompatibilityKey,
nil];
CVPixelBufferRef pxbuffer = NULL;
CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, frameSize.width,
frameSize.height, kCVPixelFormatType_32ARGB, (CFDictionaryRef) CFBridgingRetain(options),
&pxbuffer);
NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
CVPixelBufferLockBaseAddress(pxbuffer, 0);
void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(pxdata, frameSize.width,
frameSize.height, 8, 4*frameSize.width, rgbColorSpace,
kCGImageAlphaPremultipliedFirst);
CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
CGImageGetHeight(image)), image);
CGColorSpaceRelease(rgbColorSpace);
CGContextRelease(context);
CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
return pxbuffer;
}
#pragma mark - Protocol AVCaptureVideoDataOutputSampleBufferDelegate
......@@ -522,7 +551,8 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
}
if (self.recordAssetWriterInput.readyForMoreMediaData) {
if (! [self.recordPixelBufferAdaptor appendPixelBuffer:imageBuffer
CVImageBufferRef pixelBuffer = [self pixelBufferFromCGImage:dstImage];
if (! [self.recordPixelBufferAdaptor appendPixelBuffer:pixelBuffer
withPresentationTime:lastSampleTime] ) {
NSLog(@"Video Writing Error");
}
......@@ -543,9 +573,12 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
- (void)updateOrientation;
{
NSLog(@"rotate..");
self.customPreviewLayer.bounds = CGRectMake(0, 0, self.parentView.frame.size.width, self.parentView.frame.size.height);
[self layoutPreviewLayer];
if (self.rotateVideo == YES)
{
NSLog(@"rotate..");
self.customPreviewLayer.bounds = CGRectMake(0, 0, self.parentView.frame.size.width, self.parentView.frame.size.height);
[self layoutPreviewLayer];
}
}
......@@ -583,3 +616,4 @@ static CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / 180;};
}
@end
......@@ -2473,35 +2473,33 @@ void DefaultViewPort::saveView()
if (!fileName.isEmpty()) //save the picture
{
QString extension = fileName.right(3);
// (no need anymore) create the image resized to receive the 'screenshot'
// image2Draw_qt_resized = QImage(viewport()->width(), viewport()->height(),QImage::Format_RGB888);
QPainter saveimage(&image2Draw_qt_resized);
this->render(&saveimage);
// Create a new pixmap to render the viewport into
QPixmap viewportPixmap(viewport()->size());
viewport()->render(&viewportPixmap);
// Save it..
if (QString::compare(extension, "png", Qt::CaseInsensitive) == 0)
{
image2Draw_qt_resized.save(fileName, "PNG");
viewportPixmap.save(fileName, "PNG");
return;
}
if (QString::compare(extension, "jpg", Qt::CaseInsensitive) == 0)
{
image2Draw_qt_resized.save(fileName, "JPG");
viewportPixmap.save(fileName, "JPG");
return;
}
if (QString::compare(extension, "bmp", Qt::CaseInsensitive) == 0)
{
image2Draw_qt_resized.save(fileName, "BMP");
viewportPixmap.save(fileName, "BMP");
return;
}
if (QString::compare(extension, "jpeg", Qt::CaseInsensitive) == 0)
{
image2Draw_qt_resized.save(fileName, "JPEG");
viewportPixmap.save(fileName, "JPEG");
return;
}
......@@ -2651,17 +2649,16 @@ void DefaultViewPort::paintEvent(QPaintEvent* evnt)
//Now disable matrixWorld for overlay display
myPainter.setWorldMatrixEnabled(false);
//overlay pixel values if zoomed in far enough
if (param_matrixWorld.m11()*ratioX >= threshold_zoom_img_region &&
param_matrixWorld.m11()*ratioY >= threshold_zoom_img_region)
{
drawImgRegion(&myPainter);
}
//in mode zoom/panning
if (param_matrixWorld.m11() > 1)
{
if (param_matrixWorld.m11() >= threshold_zoom_img_region)
{
if (centralWidget->param_flags == CV_WINDOW_NORMAL)
startDisplayInfo("WARNING: The values displayed are the resized image's values. If you want the original image's values, use CV_WINDOW_AUTOSIZE", 1000);
drawImgRegion(&myPainter);
}
drawViewOverview(&myPainter);
}
......@@ -2887,22 +2884,24 @@ void DefaultViewPort::drawStatusBar()
//accept only CV_8UC1 and CV_8UC8 image for now
void DefaultViewPort::drawImgRegion(QPainter *painter)
{
if (nbChannelOriginImage!=CV_8UC1 && nbChannelOriginImage!=CV_8UC3)
return;
qreal offsetX = param_matrixWorld.dx()/param_matrixWorld.m11();
double pixel_width = param_matrixWorld.m11()*ratioX;
double pixel_height = param_matrixWorld.m11()*ratioY;
qreal offsetX = param_matrixWorld.dx()/pixel_width;
offsetX = offsetX - floor(offsetX);
qreal offsetY = param_matrixWorld.dy()/param_matrixWorld.m11();
qreal offsetY = param_matrixWorld.dy()/pixel_height;
offsetY = offsetY - floor(offsetY);
QSize view = size();
QVarLengthArray<QLineF, 30> linesX;
for (qreal _x = offsetX*param_matrixWorld.m11(); _x < view.width(); _x += param_matrixWorld.m11() )
for (qreal _x = offsetX*pixel_width; _x < view.width(); _x += pixel_width )
linesX.append(QLineF(_x, 0, _x, view.height()));
QVarLengthArray<QLineF, 30> linesY;
for (qreal _y = offsetY*param_matrixWorld.m11(); _y < view.height(); _y += param_matrixWorld.m11() )
for (qreal _y = offsetY*pixel_height; _y < view.height(); _y += pixel_height )
linesY.append(QLineF(0, _y, view.width(), _y));
......@@ -2910,27 +2909,25 @@ void DefaultViewPort::drawImgRegion(QPainter *painter)
int original_font_size = f.pointSize();
//change font size
//f.setPointSize(4+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
f.setPixelSize(10+(param_matrixWorld.m11()-threshold_zoom_img_region)/5);
f.setPixelSize(10+(pixel_height-threshold_zoom_img_region)/5);
painter->setFont(f);
QString val;
QRgb rgbValue;
QPointF point1;//sorry, I do not know how to name it
QPointF point2;//idem
for (int j=-1;j<height()/param_matrixWorld.m11();j++)//-1 because display the pixels top rows left colums
for (int i=-1;i<width()/param_matrixWorld.m11();i++)//-1
for (int j=-1;j<height()/pixel_height;j++)//-1 because display the pixels top rows left columns
for (int i=-1;i<width()/pixel_width;i++)//-1
{
point1.setX((i+offsetX)*param_matrixWorld.m11());
point1.setY((j+offsetY)*param_matrixWorld.m11());
matrixWorld_inv.map(point1.x(),point1.y(),&point2.rx(),&point2.ry());
point2.rx()= (long) (point2.x() + 0.5);
point2.ry()= (long) (point2.y() + 0.5);
if (point2.x() >= 0 && point2.y() >= 0)
rgbValue = image2Draw_qt_resized.pixel(QPoint(point2.x(),point2.y()));
// Calculate top left of the pixel's position in the viewport (screen space)
QPointF pos_in_view((i+offsetX)*pixel_width, (j+offsetY)*pixel_height);
// Calculate top left of the pixel's position in the image (image space)
QPointF pos_in_image = matrixWorld_inv.map(pos_in_view);// Top left of pixel in view
pos_in_image.rx() = pos_in_image.x()/ratioX;
pos_in_image.ry() = pos_in_image.y()/ratioY;
QPoint point_in_image(pos_in_image.x() + 0.5f,pos_in_image.y() + 0.5f);// Add 0.5 for rounding
QRgb rgbValue;
if (image2Draw_qt.valid(point_in_image))
rgbValue = image2Draw_qt.pixel(point_in_image);
else
rgbValue = qRgb(0,0,0);
......@@ -2943,29 +2940,29 @@ void DefaultViewPort::drawImgRegion(QPainter *painter)
painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/2),
Qt::AlignCenter, val);
*/
QString val;
val = tr("%1").arg(qRed(rgbValue));
painter->setPen(QPen(Qt::red, 1));
painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()/3),
painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height/3),
Qt::AlignCenter, val);
val = tr("%1").arg(qGreen(rgbValue));
painter->setPen(QPen(Qt::green, 1));
painter->drawText(QRect(point1.x(),point1.y()+param_matrixWorld.m11()/3,param_matrixWorld.m11(),param_matrixWorld.m11()/3),
painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+pixel_height/3,pixel_width,pixel_height/3),
Qt::AlignCenter, val);
val = tr("%1").arg(qBlue(rgbValue));
painter->setPen(QPen(Qt::blue, 1));
painter->drawText(QRect(point1.x(),point1.y()+2*param_matrixWorld.m11()/3,param_matrixWorld.m11(),param_matrixWorld.m11()/3),
painter->drawText(QRect(pos_in_view.x(),pos_in_view.y()+2*pixel_height/3,pixel_width,pixel_height/3),
Qt::AlignCenter, val);
}
if (nbChannelOriginImage==CV_8UC1)
{
val = tr("%1").arg(qRed(rgbValue));
painter->drawText(QRect(point1.x(),point1.y(),param_matrixWorld.m11(),param_matrixWorld.m11()),
QString val = tr("%1").arg(qRed(rgbValue));
painter->drawText(QRect(pos_in_view.x(),pos_in_view.y(),pixel_width,pixel_height),
Qt::AlignCenter, val);
}
}
......
......@@ -522,7 +522,6 @@ private:
CvMat* image2Draw_mat;
QImage image2Draw_qt;
QImage image2Draw_qt_resized;
int nbChannelOriginImage;
//for mouse callback
......
......@@ -585,4 +585,18 @@ public class Calib3dTest extends OpenCVTestCase {
public void testValidateDisparityMatMatIntIntInt() {
fail("Not yet implemented");
}
public void testComputeCorrespondEpilines()
{
Mat fundamental = new Mat(3, 3, CvType.CV_64F);
fundamental.put(0, 0, 0, -0.577, 0.288, 0.577, 0, 0.288, -0.288, -0.288, 0);
MatOfPoint2f left = new MatOfPoint2f();
left.alloc(1);
left.put(0, 0, 2, 3); //add(new Point(x, y));
Mat lines = new Mat();
Mat truth = new Mat(1, 1, CvType.CV_32FC3);
truth.put(0, 0, -0.70735186, 0.70686162, -0.70588124);
Calib3d.computeCorrespondEpilines(left, 1, fundamental, lines);
assertMatEqual(truth, lines, EPS);
}
}
......@@ -1149,3 +1149,76 @@ protected:
TEST(Features2d_SIFTHomographyTest, regression) { CV_DetectPlanarTest test("SIFT", 80); test.safe_run(); }
TEST(Features2d_SURFHomographyTest, regression) { CV_DetectPlanarTest test("SURF", 80); test.safe_run(); }
class FeatureDetectorUsingMaskTest : public cvtest::BaseTest
{
public:
FeatureDetectorUsingMaskTest(const Ptr<FeatureDetector>& featureDetector) :
featureDetector_(featureDetector)
{
CV_Assert(!featureDetector_.empty());
}
protected:
void run(int)
{
const int nStepX = 2;
const int nStepY = 2;
const string imageFilename = string(ts->get_data_path()) + "/features2d/tsukuba.png";
Mat image = imread(imageFilename);
if(image.empty())
{
ts->printf(cvtest::TS::LOG, "Image %s can not be read.\n", imageFilename.c_str());
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_TEST_DATA);
return;
}
Mat mask(image.size(), CV_8U);
const int stepX = image.size().width / nStepX;
const int stepY = image.size().height / nStepY;
vector<KeyPoint> keyPoints;
vector<Point2f> points;
for(int i=0; i<nStepX; ++i)
for(int j=0; j<nStepY; ++j)
{
mask.setTo(0);
Rect whiteArea(i * stepX, j * stepY, stepX, stepY);
mask(whiteArea).setTo(255);
featureDetector_->detect(image, keyPoints, mask);
KeyPoint::convert(keyPoints, points);
for(size_t k=0; k<points.size(); ++k)
{
if ( !whiteArea.contains(points[k]) )
{
ts->printf(cvtest::TS::LOG, "The feature point is outside of the mask.");
ts->set_failed_test_info(cvtest::TS::FAIL_INVALID_OUTPUT);
return;
}
}
}
ts->set_failed_test_info( cvtest::TS::OK );
}
Ptr<FeatureDetector> featureDetector_;
};
TEST(Features2d_SIFT_using_mask, regression)
{
FeatureDetectorUsingMaskTest test(Algorithm::create<FeatureDetector>("Feature2D.SIFT"));
test.safe_run();
}
TEST(DISABLED_Features2d_SURF_using_mask, regression)
{
FeatureDetectorUsingMaskTest test(Algorithm::create<FeatureDetector>("Feature2D.SURF"));
test.safe_run();
}
......@@ -245,6 +245,11 @@ namespace cv
operator Mat() const;
void download(cv::Mat &m) const;
//! convert to _InputArray
operator _InputArray();
//! convert to _OutputArray
operator _OutputArray();
//! returns a new oclMatrix header for the specified row
oclMat row(int y) const;
......@@ -386,6 +391,9 @@ namespace cv
int wholecols;
};
// convert InputArray/OutputArray to oclMat references
CV_EXPORTS oclMat& getOclMatRef(InputArray src);
CV_EXPORTS oclMat& getOclMatRef(OutputArray src);
///////////////////// mat split and merge /////////////////////////////////
//! Compose a multi-channel array from several single-channel arrays
......
......@@ -113,7 +113,7 @@ namespace cv
size_t localThreads[3], std::vector< std::pair<size_t, const void *> > &args, int channels, int depth, FLUSH_MODE finish_mode = DISABLE);
void CV_EXPORTS openCLExecuteKernel2(Context *clCxt , const char **source, String kernelName, size_t globalThreads[3],
size_t localThreads[3], std::vector< std::pair<size_t, const void *> > &args, int channels,
int depth, char *build_options, FLUSH_MODE finish_mode = DISABLE);
int depth, const char *build_options, FLUSH_MODE finish_mode = DISABLE);
// bind oclMat to OpenCL image textures
// note:
// 1. there is no memory management. User need to explicitly release the resource
......
......@@ -52,6 +52,8 @@ int main(int argc, const char *argv[])
cerr << "no device found\n";
return -1;
}
// set this to overwrite binary cache every time the test starts
ocl::setBinaryDiskCache(ocl::CACHE_UPDATE);
int devidx = 0;
......
......@@ -15,8 +15,8 @@
// Third party copyrights are property of their respective owners.
//
// @Authors
// Chunpeng Zhang chunpeng@multicorewareinc.com
//
// Fangfang Bai, fangfang@multicorewareinc.com
// Jin Ma, jin@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
......@@ -31,7 +31,7 @@
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// This software is provided by the copyright holders and contributors as is and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
......@@ -45,50 +45,57 @@
//M*/
#include "precomp.hpp"
#include <iomanip>
///////////// StereoMatchBM ////////////////////////
PERFTEST(StereoMatchBM)
{
Mat left_image = imread(abspath("aloeL.jpg"), cv::IMREAD_GRAYSCALE);
Mat right_image = imread(abspath("aloeR.jpg"), cv::IMREAD_GRAYSCALE);
Mat disp,dst;
ocl::oclMat d_left, d_right,d_disp;
int n_disp= 128;
int winSize =19;
#ifdef HAVE_OPENCL
SUBTEST << left_image.cols << 'x' << left_image.rows << "; aloeL.jpg ;"<< right_image.cols << 'x' << right_image.rows << "; aloeR.jpg ";
PARAM_TEST_CASE(ColumnSum, cv::Size)
{
cv::Size size;
cv::Mat src;
Ptr<StereoBM> bm = createStereoBM(n_disp, winSize);
bm->compute(left_image, right_image, dst);
virtual void SetUp()
{
size = GET_PARAM(0);
}
};
CPU_ON;
bm->compute(left_image, right_image, dst);
CPU_OFF;
TEST_P(ColumnSum, Accuracy)
{
cv::Mat src = randomMat(size, CV_32FC1);
cv::ocl::oclMat d_dst;
cv::ocl::oclMat d_src(src);
cv::ocl::columnSum(d_src, d_dst);
cv::Mat dst(d_dst);
for (int j = 0; j < src.cols; ++j)
{
float gold = src.at<float>(0, j);
float res = dst.at<float>(0, j);
ASSERT_NEAR(res, gold, 1e-5);
}
for (int i = 1; i < src.rows; ++i)
{
for (int j = 0; j < src.cols; ++j)
{
float gold = src.at<float>(i, j) += src.at<float>(i - 1, j);
float res = dst.at<float>(i, j);
ASSERT_NEAR(res, gold, 1e-5);
}
}
d_left.upload(left_image);
d_right.upload(right_image);
ocl::StereoBM_OCL d_bm(0, n_disp, winSize);
WARMUP_ON;
d_bm(d_left, d_right, d_disp);
WARMUP_OFF;
cv::Mat ocl_mat;
d_disp.download(ocl_mat);
ocl_mat.convertTo(ocl_mat, dst.type());
GPU_ON;
d_bm(d_left, d_right, d_disp);
GPU_OFF;
GPU_FULL_ON;
d_left.upload(left_image);
d_right.upload(right_image);
d_bm(d_left, d_right, d_disp);
d_disp.download(disp);
GPU_FULL_OFF;
TestSystem::instance().setAccurate(-1, 0.);
}
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, ColumnSum, DIFFERENT_SIZES);
#endif
\ No newline at end of file
......@@ -284,6 +284,7 @@ PERFTEST(GaussianBlur)
Mat src, dst, ocl_dst;
int all_type[] = {CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4};
std::string type_name[] = {"CV_8UC1", "CV_8UC4", "CV_32FC1", "CV_32FC4"};
const int ksize = 7;
for (int size = Min_Size; size <= Max_Size; size *= Multiple)
{
......@@ -291,29 +292,28 @@ PERFTEST(GaussianBlur)
{
SUBTEST << size << 'x' << size << "; " << type_name[j] ;
gen(src, size, size, all_type[j], 5, 16);
gen(src, size, size, all_type[j], 0, 256);
GaussianBlur(src, dst, Size(9, 9), 0);
GaussianBlur(src, dst, Size(ksize, ksize), 0);
CPU_ON;
GaussianBlur(src, dst, Size(9, 9), 0);
GaussianBlur(src, dst, Size(ksize, ksize), 0);
CPU_OFF;
ocl::oclMat d_src(src);
ocl::oclMat d_dst(src.size(), src.type());
ocl::oclMat d_buf;
ocl::oclMat d_dst;
WARMUP_ON;
ocl::GaussianBlur(d_src, d_dst, Size(9, 9), 0);
ocl::GaussianBlur(d_src, d_dst, Size(ksize, ksize), 0);
WARMUP_OFF;
GPU_ON;
ocl::GaussianBlur(d_src, d_dst, Size(9, 9), 0);
ocl::GaussianBlur(d_src, d_dst, Size(ksize, ksize), 0);
GPU_OFF;
GPU_FULL_ON;
d_src.upload(src);
ocl::GaussianBlur(d_src, d_dst, Size(9, 9), 0);
ocl::GaussianBlur(d_src, d_dst, Size(ksize, ksize), 0);
d_dst.download(ocl_dst);
GPU_FULL_OFF;
......
......@@ -46,11 +46,6 @@
#include "precomp.hpp"
///////////// HOG////////////////////////
bool match_rect(cv::Rect r1, cv::Rect r2, int threshold)
{
return ((abs(r1.x - r2.x) < threshold) && (abs(r1.y - r2.y) < threshold) &&
(abs(r1.width - r2.width) < threshold) && (abs(r1.height - r2.height) < threshold));
}
PERFTEST(HOG)
{
......@@ -61,13 +56,12 @@ PERFTEST(HOG)
throw runtime_error("can't open road.png");
}
cv::HOGDescriptor hog;
hog.setSVMDetector(hog.getDefaultPeopleDetector());
std::vector<cv::Rect> found_locations;
std::vector<cv::Rect> d_found_locations;
SUBTEST << 768 << 'x' << 576 << "; road.png";
SUBTEST << src.cols << 'x' << src.rows << "; road.png";
hog.detectMultiScale(src, found_locations);
......@@ -84,70 +78,10 @@ PERFTEST(HOG)
ocl_hog.detectMultiScale(d_src, d_found_locations);
WARMUP_OFF;
// Ground-truth rectangular people window
cv::Rect win1_64x128(231, 190, 72, 144);
cv::Rect win2_64x128(621, 156, 97, 194);
cv::Rect win1_48x96(238, 198, 63, 126);
cv::Rect win2_48x96(619, 161, 92, 185);
cv::Rect win3_48x96(488, 136, 56, 112);
// Compare whether ground-truth windows are detected and compare the number of windows detected.
std::vector<int> d_comp(4);
std::vector<int> comp(4);
for(int i = 0; i < (int)d_comp.size(); i++)
{
d_comp[i] = 0;
comp[i] = 0;
}
int threshold = 10;
int val = 32;
d_comp[0] = (int)d_found_locations.size();
comp[0] = (int)found_locations.size();
cv::Size winSize = hog.winSize;
if (winSize == cv::Size(48, 96))
{
for(int i = 0; i < (int)d_found_locations.size(); i++)
{
if (match_rect(d_found_locations[i], win1_48x96, threshold))
d_comp[1] = val;
if (match_rect(d_found_locations[i], win2_48x96, threshold))
d_comp[2] = val;
if (match_rect(d_found_locations[i], win3_48x96, threshold))
d_comp[3] = val;
}
for(int i = 0; i < (int)found_locations.size(); i++)
{
if (match_rect(found_locations[i], win1_48x96, threshold))
comp[1] = val;
if (match_rect(found_locations[i], win2_48x96, threshold))
comp[2] = val;
if (match_rect(found_locations[i], win3_48x96, threshold))
comp[3] = val;
}
}
else if (winSize == cv::Size(64, 128))
{
for(int i = 0; i < (int)d_found_locations.size(); i++)
{
if (match_rect(d_found_locations[i], win1_64x128, threshold))
d_comp[1] = val;
if (match_rect(d_found_locations[i], win2_64x128, threshold))
d_comp[2] = val;
}
for(int i = 0; i < (int)found_locations.size(); i++)
{
if (match_rect(found_locations[i], win1_64x128, threshold))
comp[1] = val;
if (match_rect(found_locations[i], win2_64x128, threshold))
comp[2] = val;
}
}
cv::Mat gpu_rst(d_comp), cpu_rst(comp);
TestSystem::instance().ExpectedMatNear(gpu_rst, cpu_rst, 3);
if(d_found_locations.size() == found_locations.size())
TestSystem::instance().setAccurate(1, 0);
else
TestSystem::instance().setAccurate(0, abs((int)found_locations.size() - (int)d_found_locations.size()));
GPU_ON;
ocl_hog.detectMultiScale(d_src, found_locations);
......
......@@ -743,12 +743,12 @@ PERFTEST(meanShiftFiltering)
WARMUP_OFF;
GPU_ON;
ocl::meanShiftFiltering(d_src, d_dst, sp, sr);
ocl::meanShiftFiltering(d_src, d_dst, sp, sr, crit);
GPU_OFF;
GPU_FULL_ON;
d_src.upload(src);
ocl::meanShiftFiltering(d_src, d_dst, sp, sr);
ocl::meanShiftFiltering(d_src, d_dst, sp, sr, crit);
d_dst.download(ocl_dst);
GPU_FULL_OFF;
......@@ -969,3 +969,45 @@ PERFTEST(CLAHE)
}
}
}
///////////// columnSum////////////////////////
PERFTEST(columnSum)
{
Mat src, dst, ocl_dst;
ocl::oclMat d_src, d_dst;
for (int size = Min_Size; size <= Max_Size; size *= Multiple)
{
SUBTEST << size << 'x' << size << "; CV_32FC1";
gen(src, size, size, CV_32FC1, 0, 256);
CPU_ON;
dst.create(src.size(), src.type());
for (int j = 0; j < src.cols; j++)
dst.at<float>(0, j) = src.at<float>(0, j);
for (int i = 1; i < src.rows; ++i)
for (int j = 0; j < src.cols; ++j)
dst.at<float>(i, j) = dst.at<float>(i - 1 , j) + src.at<float>(i , j);
CPU_OFF;
d_src.upload(src);
WARMUP_ON;
ocl::columnSum(d_src, d_dst);
WARMUP_OFF;
GPU_ON;
ocl::columnSum(d_src, d_dst);
GPU_OFF;
GPU_FULL_ON;
d_src.upload(src);
ocl::columnSum(d_src, d_dst);
d_dst.download(ocl_dst);
GPU_FULL_OFF;
TestSystem::instance().ExpectedMatNear(dst, ocl_dst, 5e-1);
}
}
......@@ -44,45 +44,49 @@
//
//M*/
#include "precomp.hpp"
///////////// columnSum////////////////////////
PERFTEST(columnSum)
///////////// Moments ////////////////////////
PERFTEST(Moments)
{
Mat src, dst, ocl_dst;
ocl::oclMat d_src, d_dst;
Mat src;
bool binaryImage = 0;
int all_type[] = {CV_8UC1, CV_16SC1, CV_32FC1, CV_64FC1};
std::string type_name[] = {"CV_8UC1", "CV_16SC1", "CV_32FC1", "CV_64FC1"};
for (int size = Min_Size; size <= Max_Size; size *= Multiple)
{
SUBTEST << size << 'x' << size << "; CV_32FC1";
for (size_t j = 0; j < sizeof(all_type) / sizeof(int); j++)
{
SUBTEST << size << 'x' << size << "; " << type_name[j];
gen(src, size, size, all_type[j], 0, 256);
cv::Moments CvMom = moments(src, binaryImage);
gen(src, size, size, CV_32FC1, 0, 256);
CPU_ON;
moments(src, binaryImage);
CPU_OFF;
CPU_ON;
dst.create(src.size(), src.type());
for (int j = 0; j < src.cols; j++)
dst.at<float>(0, j) = src.at<float>(0, j);
cv::Moments oclMom;
WARMUP_ON;
oclMom = ocl::ocl_moments(src, binaryImage);
WARMUP_OFF;
for (int i = 1; i < src.rows; ++i)
for (int j = 0; j < src.cols; ++j)
dst.at<float>(i, j) = dst.at<float>(i - 1 , j) + src.at<float>(i , j);
CPU_OFF;
Mat gpu_dst, cpu_dst;
HuMoments(CvMom, cpu_dst);
HuMoments(oclMom, gpu_dst);
d_src.upload(src);
GPU_ON;
ocl::ocl_moments(src, binaryImage);
GPU_OFF;
WARMUP_ON;
ocl::columnSum(d_src, d_dst);
WARMUP_OFF;
GPU_FULL_ON;
ocl::ocl_moments(src, binaryImage);
GPU_FULL_OFF;
GPU_ON;
ocl::columnSum(d_src, d_dst);
GPU_OFF;
TestSystem::instance().ExpectedMatNear(gpu_dst, cpu_dst, .5);
GPU_FULL_ON;
d_src.upload(src);
ocl::columnSum(d_src, d_dst);
d_dst.download(ocl_dst);
GPU_FULL_OFF;
}
TestSystem::instance().ExpectedMatNear(dst, ocl_dst, 5e-1);
}
}
\ No newline at end of file
}
......@@ -331,20 +331,6 @@ void TestSystem::printMetrics(int is_accurate, double cpu_time, double gpu_time,
cout << setiosflags(ios_base::left);
stringstream stream;
#if 0
if(is_accurate == 1)
stream << "Pass";
else if(is_accurate_ == 0)
stream << "Fail";
else if(is_accurate == -1)
stream << " ";
else
{
std::cout<<"is_accurate errer: "<<is_accurate<<"\n";
exit(-1);
}
#endif
std::stringstream &cur_subtest_description = getCurSubtestDescription();
#if GTEST_OS_WINDOWS&&!GTEST_OS_WINDOWS_MOBILE
......
This diff is collapsed.
......@@ -73,6 +73,7 @@ namespace cv
}
}
////////////////////////////////////////////////////////////////////////
// convert_C3C4
static void convert_C3C4(const cl_mem &src, oclMat &dst)
......@@ -215,6 +216,34 @@ void cv::ocl::oclMat::upload(const Mat &m)
offset = ofs.y * step + ofs.x * elemSize();
}
cv::ocl::oclMat::operator cv::_InputArray()
{
_InputArray newInputArray;
newInputArray.flags = cv::_InputArray::OCL_MAT;
newInputArray.obj = reinterpret_cast<void *>(this);
return newInputArray;
}
cv::ocl::oclMat::operator cv::_OutputArray()
{
_OutputArray newOutputArray;
newOutputArray.flags = cv::_InputArray::OCL_MAT;
newOutputArray.obj = reinterpret_cast<void *>(this);
return newOutputArray;
}
cv::ocl::oclMat& cv::ocl::getOclMatRef(InputArray src)
{
CV_Assert(src.flags & cv::_InputArray::OCL_MAT);
return *reinterpret_cast<oclMat*>(src.obj);
}
cv::ocl::oclMat& cv::ocl::getOclMatRef(OutputArray src)
{
CV_Assert(src.flags & cv::_InputArray::OCL_MAT);
return *reinterpret_cast<oclMat*>(src.obj);
}
void cv::ocl::oclMat::download(cv::Mat &m) const
{
CV_DbgAssert(!this->empty());
......@@ -382,7 +411,7 @@ void cv::ocl::oclMat::convertTo( oclMat &dst, int rtype, double alpha, double be
if( rtype < 0 )
rtype = type();
else
rtype = CV_MAKETYPE(CV_MAT_DEPTH(rtype), oclchannels());
rtype = CV_MAKETYPE(CV_MAT_DEPTH(rtype), channels());
//int scn = channels();
int sdepth = depth(), ddepth = CV_MAT_DEPTH(rtype);
......
......@@ -80,7 +80,7 @@ namespace cv
// provide additional methods for the user to interact with the command queue after a task is fired
static void openCLExecuteKernel_2(Context *clCxt , const char **source, String kernelName, size_t globalThreads[3],
size_t localThreads[3], std::vector< std::pair<size_t, const void *> > &args, int channels,
int depth, char *build_options, FLUSH_MODE finish_mode)
int depth, const char *build_options, FLUSH_MODE finish_mode)
{
//construct kernel name
//The rule is functionName_Cn_Dn, C represent Channels, D Represent DataType Depth, n represent an integer number
......@@ -133,7 +133,7 @@ namespace cv
}
void openCLExecuteKernel2(Context *clCxt , const char **source, String kernelName,
size_t globalThreads[3], size_t localThreads[3],
std::vector< std::pair<size_t, const void *> > &args, int channels, int depth, char *build_options, FLUSH_MODE finish_mode)
std::vector< std::pair<size_t, const void *> > &args, int channels, int depth, const char *build_options, FLUSH_MODE finish_mode)
{
openCLExecuteKernel_2(clCxt, source, kernelName, globalThreads, localThreads, args, channels, depth,
......
This diff is collapsed.
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Institute Of Software Chinese Academy Of Science, all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Jia Haipeng, jiahaipeng95@gmail.com
// Sen Liu, swjutls1987@126.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "opencv2/objdetect.hpp"
#include "precomp.hpp"
#if 0 //def HAVE_OPENCL
using namespace cvtest;
using namespace testing;
using namespace std;
using namespace cv;
extern string workdir;
namespace
{
IMPLEMENT_PARAM_CLASS(CascadeName, std::string);
CascadeName cascade_frontalface_alt(std::string("haarcascade_frontalface_alt.xml"));
CascadeName cascade_frontalface_alt2(std::string("haarcascade_frontalface_alt2.xml"));
struct getRect
{
Rect operator ()(const CvAvgComp &e) const
{
return e.rect;
}
};
}
PARAM_TEST_CASE(Haar, double, int, CascadeName)
{
cv::ocl::OclCascadeClassifier cascade, nestedCascade;
cv::CascadeClassifier cpucascade, cpunestedCascade;
double scale;
int flags;
std::string cascadeName;
virtual void SetUp()
{
scale = GET_PARAM(0);
flags = GET_PARAM(1);
cascadeName = (workdir + "../../data/haarcascades/").append(GET_PARAM(2));
if( (!cascade.load( cascadeName )) || (!cpucascade.load(cascadeName)) )
{
cout << "ERROR: Could not load classifier cascade" << endl;
return;
}
}
};
////////////////////////////////faceDetect/////////////////////////////////////////////////
TEST_P(Haar, FaceDetect)
{
string imgName = workdir + "lena.jpg";
Mat img = imread( imgName, 1 );
if(img.empty())
{
std::cout << "Couldn't read " << imgName << std::endl;
return ;
}
vector<Rect> faces, oclfaces;
Mat gray, smallImg(cvRound (img.rows / scale), cvRound(img.cols / scale), CV_8UC1 );
MemStorage storage(cvCreateMemStorage(0));
cvtColor( img, gray, COLOR_BGR2GRAY );
resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
equalizeHist( smallImg, smallImg );
cv::ocl::oclMat image;
CvSeq *_objects;
image.upload(smallImg);
_objects = cascade.oclHaarDetectObjects( image, storage, 1.1,
3, flags, Size(30, 30), Size(0, 0) );
vector<CvAvgComp> vecAvgComp;
Seq<CvAvgComp>(_objects).copyTo(vecAvgComp);
oclfaces.resize(vecAvgComp.size());
std::transform(vecAvgComp.begin(), vecAvgComp.end(), oclfaces.begin(), getRect());
cpucascade.detectMultiScale( smallImg, faces, 1.1, 3,
flags,
Size(30, 30), Size(0, 0) );
EXPECT_EQ(faces.size(), oclfaces.size());
}
TEST_P(Haar, FaceDetectUseBuf)
{
string imgName = workdir + "lena.jpg";
Mat img = imread( imgName, 1 );
if(img.empty())
{
std::cout << "Couldn't read " << imgName << std::endl;
return ;
}
vector<Rect> faces, oclfaces;
Mat gray, smallImg(cvRound (img.rows / scale), cvRound(img.cols / scale), CV_8UC1 );
cvtColor( img, gray, CV_BGR2GRAY );
resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
equalizeHist( smallImg, smallImg );
cv::ocl::oclMat image;
image.upload(smallImg);
cv::ocl::OclCascadeClassifierBuf cascadebuf;
if( !cascadebuf.load( cascadeName ) )
{
cout << "ERROR: Could not load classifier cascade for FaceDetectUseBuf!" << endl;
return;
}
cascadebuf.detectMultiScale( image, oclfaces, 1.1, 3,
flags,
Size(30, 30), Size(0, 0) );
cpucascade.detectMultiScale( smallImg, faces, 1.1, 3,
flags,
Size(30, 30), Size(0, 0) );
EXPECT_EQ(faces.size(), oclfaces.size());
// intentionally run ocl facedetect again and check if it still works after the first run
cascadebuf.detectMultiScale( image, oclfaces, 1.1, 3,
flags,
Size(30, 30));
cascadebuf.release();
EXPECT_EQ(faces.size(), oclfaces.size());
}
INSTANTIATE_TEST_CASE_P(FaceDetect, Haar,
Combine(Values(1.0),
Values(CV_HAAR_SCALE_IMAGE, 0), Values(cascade_frontalface_alt, cascade_frontalface_alt2)));
#endif // HAVE_OPENCL
......@@ -1573,6 +1573,47 @@ TEST_P(Convolve, Mat)
}
}
//////////////////////////////// ColumnSum //////////////////////////////////////
PARAM_TEST_CASE(ColumnSum, cv::Size)
{
cv::Size size;
cv::Mat src;
virtual void SetUp()
{
size = GET_PARAM(0);
}
};
TEST_P(ColumnSum, Accuracy)
{
cv::Mat src = randomMat(size, CV_32FC1);
cv::ocl::oclMat d_dst;
cv::ocl::oclMat d_src(src);
cv::ocl::columnSum(d_src, d_dst);
cv::Mat dst(d_dst);
for (int j = 0; j < src.cols; ++j)
{
float gold = src.at<float>(0, j);
float res = dst.at<float>(0, j);
ASSERT_NEAR(res, gold, 1e-5);
}
for (int i = 1; i < src.rows; ++i)
{
for (int j = 0; j < src.cols; ++j)
{
float gold = src.at<float>(i, j) += src.at<float>(i - 1, j);
float res = dst.at<float>(i, j);
ASSERT_NEAR(res, gold, 1e-5);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////
INSTANTIATE_TEST_CASE_P(ImgprocTestBase, equalizeHist, Combine(
ONE_TYPE(CV_8UC1),
NULL_TYPE,
......@@ -1688,7 +1729,6 @@ INSTANTIATE_TEST_CASE_P(ImgProc, CLAHE, Combine(
Values(cv::Size(128, 128), cv::Size(113, 113), cv::Size(1300, 1300)),
Values(0.0, 40.0)));
//INSTANTIATE_TEST_CASE_P(ConvolveTestBase, Convolve, Combine(
// Values(CV_32FC1, CV_32FC1),
// Values(false))); // Values(false) is the reserved parameter
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, ColumnSum, DIFFERENT_SIZES);
#endif // HAVE_OPENCL
......@@ -15,7 +15,6 @@
// Third party copyrights are property of their respective owners.
//
// @Authors
// Dachuan Zhao, dachuan@multicorewareinc.com
// Yao Wang yao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
......@@ -56,11 +55,12 @@ using namespace cvtest;
using namespace testing;
using namespace std;
PARAM_TEST_CASE(PyrDown, MatType, int)
PARAM_TEST_CASE(PyrBase, MatType, int)
{
int type;
int channels;
Mat dst_cpu;
oclMat gdst;
virtual void SetUp()
{
type = GET_PARAM(0);
......@@ -69,19 +69,19 @@ PARAM_TEST_CASE(PyrDown, MatType, int)
};
/////////////////////// PyrDown //////////////////////////
struct PyrDown : PyrBase {};
TEST_P(PyrDown, Mat)
{
for(int j = 0; j < LOOP_TIMES; j++)
{
cv::Size size(MWIDTH, MHEIGHT);
cv::RNG &rng = TS::ptr()->get_rng();
cv::Mat src = randomMat(rng, size, CV_MAKETYPE(type, channels), 0, 100, false);
cv::ocl::oclMat gsrc(src), gdst;
cv::Mat dst_cpu;
cv::pyrDown(src, dst_cpu);
cv::ocl::pyrDown(gsrc, gdst);
Size size(MWIDTH, MHEIGHT);
Mat src = randomMat(size, CV_MAKETYPE(type, channels));
oclMat gsrc(src);
pyrDown(src, dst_cpu);
pyrDown(gsrc, gdst);
EXPECT_MAT_NEAR(dst_cpu, Mat(gdst), type == CV_32F ? 1e-4f : 1.0f);
}
......@@ -90,5 +90,27 @@ TEST_P(PyrDown, Mat)
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, PyrDown, Combine(
Values(CV_8U, CV_32F), Values(1, 3, 4)));
/////////////////////// PyrUp //////////////////////////
struct PyrUp : PyrBase {};
TEST_P(PyrUp, Accuracy)
{
for(int j = 0; j < LOOP_TIMES; j++)
{
Size size(MWIDTH, MHEIGHT);
Mat src = randomMat(size, CV_MAKETYPE(type, channels));
oclMat gsrc(src);
pyrUp(src, dst_cpu);
pyrUp(gsrc, gdst);
EXPECT_MAT_NEAR(dst_cpu, Mat(gdst), (type == CV_32F ? 1e-4f : 1.0));
}
}
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, PyrUp, testing::Combine(
Values(CV_8U, CV_32F), Values(1, 3, 4)));
#endif // HAVE_OPENCL
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Zhang Chunpeng chunpeng@multicorewareinc.com
// Yao Wang yao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#ifdef HAVE_OPENCL
using namespace cv;
using namespace cvtest;
using namespace testing;
using namespace std;
PARAM_TEST_CASE(PyrUp, MatType, int)
{
int type;
int channels;
virtual void SetUp()
{
type = GET_PARAM(0);
channels = GET_PARAM(1);
}
};
TEST_P(PyrUp, Accuracy)
{
for(int j = 0; j < LOOP_TIMES; j++)
{
Size size(MWIDTH, MHEIGHT);
Mat src = randomMat(size, CV_MAKETYPE(type, channels));
Mat dst_gold;
pyrUp(src, dst_gold);
ocl::oclMat dst;
ocl::oclMat srcMat(src);
ocl::pyrUp(srcMat, dst);
EXPECT_MAT_NEAR(dst_gold, Mat(dst), (type == CV_32F ? 1e-4f : 1.0));
}
}
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, PyrUp, testing::Combine(
Values(CV_8U, CV_32F), Values(1, 3, 4)));
#endif // HAVE_OPENCL
\ No newline at end of file
......@@ -100,12 +100,6 @@ Mat randomMat(Size size, int type, double minVal, double maxVal)
return randomMat(TS::ptr()->get_rng(), size, type, minVal, maxVal, false);
}
/*
void showDiff(InputArray gold_, InputArray actual_, double eps)
{
......@@ -137,58 +131,7 @@ void showDiff(InputArray gold_, InputArray actual_, double eps)
}
*/
/*
bool supportFeature(const DeviceInfo& info, FeatureSet feature)
{
return TargetArchs::builtWith(feature) && info.supports(feature);
}
const vector<DeviceInfo>& devices()
{
static vector<DeviceInfo> devs;
static bool first = true;
if (first)
{
int deviceCount = getCudaEnabledDeviceCount();
devs.reserve(deviceCount);
for (int i = 0; i < deviceCount; ++i)
{
DeviceInfo info(i);
if (info.isCompatible())
devs.push_back(info);
}
first = false;
}
return devs;
}
vector<DeviceInfo> devices(FeatureSet feature)
{
const vector<DeviceInfo>& d = devices();
vector<DeviceInfo> devs_filtered;
if (TargetArchs::builtWith(feature))
{
devs_filtered.reserve(d.size());
for (size_t i = 0, size = d.size(); i < size; ++i)
{
const DeviceInfo& info = d[i];
if (info.supports(feature))
devs_filtered.push_back(info);
}
}
return devs_filtered;
}
*/
vector<MatType> types(int depth_start, int depth_end, int cn_start, int cn_end)
{
......@@ -264,3 +207,48 @@ void PrintTo(const Inverse &inverse, std::ostream *os)
(*os) << "direct";
}
double checkRectSimilarity(Size sz, std::vector<Rect>& ob1, std::vector<Rect>& ob2)
{
double final_test_result = 0.0;
size_t sz1 = ob1.size();
size_t sz2 = ob2.size();
if(sz1 != sz2)
{
return sz1 > sz2 ? (double)(sz1 - sz2) : (double)(sz2 - sz1);
}
else
{
if(sz1==0 && sz2==0)
return 0;
cv::Mat cpu_result(sz, CV_8UC1);
cpu_result.setTo(0);
for(vector<Rect>::const_iterator r = ob1.begin(); r != ob1.end(); r++)
{
cv::Mat cpu_result_roi(cpu_result, *r);
cpu_result_roi.setTo(1);
cpu_result.copyTo(cpu_result);
}
int cpu_area = cv::countNonZero(cpu_result > 0);
cv::Mat gpu_result(sz, CV_8UC1);
gpu_result.setTo(0);
for(vector<Rect>::const_iterator r2 = ob2.begin(); r2 != ob2.end(); r2++)
{
cv::Mat gpu_result_roi(gpu_result, *r2);
gpu_result_roi.setTo(1);
gpu_result.copyTo(gpu_result);
}
cv::Mat result_;
multiply(cpu_result, gpu_result, result_);
int result = cv::countNonZero(result_ > 0);
if(cpu_area!=0 && result!=0)
final_test_result = 1.0 - (double)result/(double)cpu_area;
else if(cpu_area==0 && result!=0)
final_test_result = -1;
}
return final_test_result;
}
......@@ -57,13 +57,12 @@ cv::Mat randomMat(cv::Size size, int type, double minVal = 0.0, double maxVal =
void showDiff(cv::InputArray gold, cv::InputArray actual, double eps);
//! return true if device supports specified feature and gpu module was built with support the feature.
//bool supportFeature(const cv::gpu::DeviceInfo& info, cv::gpu::FeatureSet feature);
// This function test if gpu_rst matches cpu_rst.
// If the two vectors are not equal, it will return the difference in vector size
// Else it will return (total diff of each cpu and gpu rects covered pixels)/(total cpu rects covered pixels)
// The smaller, the better matched
double checkRectSimilarity(cv::Size sz, std::vector<cv::Rect>& ob1, std::vector<cv::Rect>& ob2);
//! return all devices compatible with current gpu module build.
//const std::vector<cv::ocl::DeviceInfo>& devices();
//! return all devices compatible with current gpu module build which support specified feature.
//std::vector<cv::ocl::DeviceInfo> devices(cv::gpu::FeatureSet feature);
//! read image from testdata folder.
cv::Mat readImage(const std::string &fileName, int flags = cv::IMREAD_COLOR);
......
......@@ -100,34 +100,39 @@ class TestInfo(object):
def dump(self, units="ms"):
print "%s ->\t\033[1;31m%s\033[0m = \t%.2f%s" % (str(self), self.status, self.get("gmean", units), units)
def shortName(self):
def getName(self):
pos = self.name.find("/")
if pos > 0:
name = self.name[:pos]
else:
name = self.name
if self.fixture.endswith(name):
fixture = self.fixture[:-len(name)]
return self.name[:pos]
return self.name
def getFixture(self):
if self.fixture.endswith(self.getName()):
fixture = self.fixture[:-len(self.getName())]
else:
fixture = self.fixture
if fixture.endswith("_"):
fixture = fixture[:-1]
return fixture
def param(self):
return '::'.join(filter(None, [self.type_param, self.value_param]))
def shortName(self):
name = self.getName()
fixture = self.getFixture()
return '::'.join(filter(None, [name, fixture]))
def __str__(self):
pos = self.name.find("/")
if pos > 0:
name = self.name[:pos]
else:
name = self.name
if self.fixture.endswith(name):
fixture = self.fixture[:-len(name)]
else:
fixture = self.fixture
if fixture.endswith("_"):
fixture = fixture[:-1]
name = self.getName()
fixture = self.getFixture()
return '::'.join(filter(None, [name, fixture, self.type_param, self.value_param]))
def __cmp__(self, other):
r = cmp(self.fixture, other.fixture);
if r != 0:
......
#!/usr/bin/env python
from __future__ import division
import ast
import logging
import numbers
import os, os.path
import re
from argparse import ArgumentParser
from collections import OrderedDict
from glob import glob
from itertools import ifilter
import xlwt
from testlog_parser import parseLogFile
# To build XLS report you neet to put your xmls (OpenCV tests output) in the
# following way:
#
# "root" --- folder, representing the whole XLS document. It contains several
# subfolders --- sheet-paths of the XLS document. Each sheet-path contains it's
# subfolders --- config-paths. Config-paths are columns of the sheet and
# they contains xmls files --- output of OpenCV modules testing.
# Config-path means OpenCV build configuration, including different
# options such as NEON, TBB, GPU enabling/disabling.
#
# root
# root\sheet_path
# root\sheet_path\configuration1 (column 1)
# root\sheet_path\configuration2 (column 2)
re_image_size = re.compile(r'^ \d+ x \d+$', re.VERBOSE)
re_data_type = re.compile(r'^ (?: 8 | 16 | 32 | 64 ) [USF] C [1234] $', re.VERBOSE)
time_style = xlwt.easyxf(num_format_str='#0.00')
no_time_style = xlwt.easyxf('pattern: pattern solid, fore_color gray25')
speedup_style = time_style
good_speedup_style = xlwt.easyxf('font: color green', num_format_str='#0.00')
bad_speedup_style = xlwt.easyxf('font: color red', num_format_str='#0.00')
no_speedup_style = no_time_style
error_speedup_style = xlwt.easyxf('pattern: pattern solid, fore_color orange')
header_style = xlwt.easyxf('font: bold true; alignment: horizontal centre, vertical top, wrap True')
def collect_xml(collection, configuration, xml_fullname):
xml_fname = os.path.split(xml_fullname)[1]
module = xml_fname[:xml_fname.index('_')]
module_tests = collection.setdefault(module, OrderedDict())
for test in sorted(parseLogFile(xml_fullname)):
test_results = module_tests.setdefault((test.shortName(), test.param()), {})
test_results[configuration] = test.get("gmean") if test.status == 'run' else test.status
def main():
arg_parser = ArgumentParser(description='Build an XLS performance report.')
arg_parser.add_argument('sheet_dirs', nargs='+', metavar='DIR', help='directory containing perf test logs')
arg_parser.add_argument('-o', '--output', metavar='XLS', default='report.xls', help='name of output file')
arg_parser.add_argument('-c', '--config', metavar='CONF', help='global configuration file')
args = arg_parser.parse_args()
logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG)
if args.config is not None:
with open(args.config) as global_conf_file:
global_conf = ast.literal_eval(global_conf_file.read())
else:
global_conf = {}
wb = xlwt.Workbook()
for sheet_path in args.sheet_dirs:
try:
with open(os.path.join(sheet_path, 'sheet.conf')) as sheet_conf_file:
sheet_conf = ast.literal_eval(sheet_conf_file.read())
except Exception:
sheet_conf = {}
logging.debug('no sheet.conf for %s', sheet_path)
sheet_conf = dict(global_conf.items() + sheet_conf.items())
if 'configurations' in sheet_conf:
config_names = sheet_conf['configurations']
else:
try:
config_names = [p for p in os.listdir(sheet_path)
if os.path.isdir(os.path.join(sheet_path, p))]
except Exception as e:
logging.warning('error while determining configuration names for %s: %s', sheet_path, e)
continue
collection = {}
for configuration, configuration_path in \
[(c, os.path.join(sheet_path, c)) for c in config_names]:
logging.info('processing %s', configuration_path)
for xml_fullname in glob(os.path.join(configuration_path, '*.xml')):
collect_xml(collection, configuration, xml_fullname)
sheet = wb.add_sheet(sheet_conf.get('sheet_name', os.path.basename(os.path.abspath(sheet_path))))
sheet.row(0).height = 800
sheet.panes_frozen = True
sheet.remove_splits = True
sheet.horz_split_pos = 1
sheet.horz_split_first_visible = 1
sheet_comparisons = sheet_conf.get('comparisons', [])
for i, w in enumerate([2000, 15000, 2500, 2000, 15000]
+ (len(config_names) + 1 + len(sheet_comparisons)) * [3000]):
sheet.col(i).width = w
for i, caption in enumerate(['Module', 'Test', 'Image\nsize', 'Data\ntype', 'Parameters']
+ config_names + [None]
+ [comp['to'] + '\nvs\n' + comp['from'] for comp in sheet_comparisons]):
sheet.row(0).write(i, caption, header_style)
row = 1
module_colors = sheet_conf.get('module_colors', {})
module_styles = {module: xlwt.easyxf('pattern: pattern solid, fore_color {}'.format(color))
for module, color in module_colors.iteritems()}
for module, tests in sorted(collection.iteritems()):
for ((test, param), configs) in tests.iteritems():
sheet.write(row, 0, module, module_styles.get(module, xlwt.Style.default_style))
sheet.write(row, 1, test)
param_list = param[1:-1].split(", ")
sheet.write(row, 2, next(ifilter(re_image_size.match, param_list), None))
sheet.write(row, 3, next(ifilter(re_data_type.match, param_list), None))
sheet.row(row).write(4, param)
for i, c in enumerate(config_names):
if c in configs:
sheet.write(row, 5 + i, configs[c], time_style)
else:
sheet.write(row, 5 + i, None, no_time_style)
for i, comp in enumerate(sheet_comparisons):
cmp_from = configs.get(comp["from"])
cmp_to = configs.get(comp["to"])
col = 5 + len(config_names) + 1 + i
if isinstance(cmp_from, numbers.Number) and isinstance(cmp_to, numbers.Number):
try:
speedup = cmp_from / cmp_to
sheet.write(row, col, speedup, good_speedup_style if speedup > 1.1 else
bad_speedup_style if speedup < 0.9 else
speedup_style)
except ArithmeticError as e:
sheet.write(row, col, None, error_speedup_style)
else:
sheet.write(row, col, None, no_speedup_style)
row += 1
if row % 1000 == 0: sheet.flush_row_data()
wb.save(args.output)
if __name__ == '__main__':
main()
......@@ -2,6 +2,10 @@
#include <float.h>
#include <limits.h>
#ifdef HAVE_TEGRA_OPTIMIZATION
#include "tegra.hpp"
#endif
using namespace cv;
namespace cvtest
......@@ -2939,28 +2943,76 @@ MatComparator::operator()(const char* expr1, const char* expr2,
void printVersionInfo(bool useStdOut)
{
::testing::Test::RecordProperty("CV_VERSION", CV_VERSION);
::testing::Test::RecordProperty("cv_version", CV_VERSION);
if(useStdOut) std::cout << "OpenCV version: " << CV_VERSION << std::endl;
std::string buildInfo( cv::getBuildInformation() );
size_t pos1 = buildInfo.find("Version control");
size_t pos2 = buildInfo.find("\n", pos1);\
size_t pos2 = buildInfo.find('\n', pos1);
if(pos1 != std::string::npos && pos2 != std::string::npos)
{
std::string ver( buildInfo.substr(pos1, pos2-pos1) );
::testing::Test::RecordProperty("Version_control", ver);
if(useStdOut) std::cout << ver << std::endl;
size_t value_start = buildInfo.rfind(' ', pos2) + 1;
std::string ver( buildInfo.substr(value_start, pos2 - value_start) );
::testing::Test::RecordProperty("cv_vcs_version", ver);
if (useStdOut) std::cout << "OpenCV VCS version: " << ver << std::endl;
}
pos1 = buildInfo.find("inner version");
pos2 = buildInfo.find("\n", pos1);\
pos2 = buildInfo.find('\n', pos1);
if(pos1 != std::string::npos && pos2 != std::string::npos)
{
std::string ver( buildInfo.substr(pos1, pos2-pos1) );
::testing::Test::RecordProperty("inner_version", ver);
if(useStdOut) std::cout << ver << std::endl;
}
size_t value_start = buildInfo.rfind(' ', pos2) + 1;
std::string ver( buildInfo.substr(value_start, pos2 - value_start) );
::testing::Test::RecordProperty("cv_inner_vcs_version", ver);
if(useStdOut) std::cout << "Inner VCS version: " << ver << std::endl;
}
#ifdef CV_PARALLEL_FRAMEWORK
::testing::Test::RecordProperty("cv_parallel_framework", CV_PARALLEL_FRAMEWORK);
if (useStdOut)
{
std::cout << "Parallel framework: " << CV_PARALLEL_FRAMEWORK << std::endl;
}
#endif
std::string cpu_features;
#if CV_SSE
if (checkHardwareSupport(CV_CPU_SSE)) cpu_features += " sse";
#endif
#if CV_SSE2
if (checkHardwareSupport(CV_CPU_SSE2)) cpu_features += " sse2";
#endif
#if CV_SSE3
if (checkHardwareSupport(CV_CPU_SSE3)) cpu_features += " sse3";
#endif
#if CV_SSSE3
if (checkHardwareSupport(CV_CPU_SSSE3)) cpu_features += " ssse3";
#endif
#if CV_SSE4_1
if (checkHardwareSupport(CV_CPU_SSE4_1)) cpu_features += " sse4.1";
#endif
#if CV_SSE4_2
if (checkHardwareSupport(CV_CPU_SSE4_2)) cpu_features += " sse4.2";
#endif
#if CV_AVX
if (checkHardwareSupport(CV_CPU_AVX)) cpu_features += " avx";
#endif
#if CV_NEON
cpu_features += " neon"; // NEON is currently not checked at runtime
#endif
cpu_features.erase(0, 1); // erase initial space
::testing::Test::RecordProperty("cv_cpu_features", cpu_features);
if (useStdOut) std::cout << "CPU features: " << cpu_features << std::endl;
#ifdef HAVE_TEGRA_OPTIMIZATION
const char * tegra_optimization = tegra::isDeviceSupported() ? "enabled" : "disabled";
::testing::Test::RecordProperty("cv_tegra_optimization", tegra_optimization);
if (useStdOut) std::cout << "Tegra optimization: " << tegra_optimization << std::endl;
#endif
}
}
......@@ -17,16 +17,19 @@ using namespace cv;
#define LOOP_NUM 10
const static Scalar colors[] = { CV_RGB(0,0,255),
CV_RGB(0,128,255),
CV_RGB(0,255,255),
CV_RGB(0,255,0),
CV_RGB(255,128,0),
CV_RGB(255,255,0),
CV_RGB(255,0,0),
CV_RGB(255,0,255)} ;
CV_RGB(0,128,255),
CV_RGB(0,255,255),
CV_RGB(0,255,0),
CV_RGB(255,128,0),
CV_RGB(255,255,0),
CV_RGB(255,0,0),
CV_RGB(255,0,255)
} ;
int64 work_begin = 0;
int64 work_end = 0;
string outputName;
static void workBegin()
{
......@@ -37,34 +40,40 @@ static void workEnd()
work_end += (getTickCount() - work_begin);
}
static double getTime(){
static double getTime()
{
return work_end /((double)cvGetTickFrequency() * 1000.);
}
void detect( Mat& img, vector<Rect>& faces,
cv::ocl::OclCascadeClassifierBuf& cascade,
double scale, bool calTime);
ocl::OclCascadeClassifierBuf& cascade,
double scale, bool calTime);
void detectCPU( Mat& img, vector<Rect>& faces,
CascadeClassifier& cascade,
double scale, bool calTime);
CascadeClassifier& cascade,
double scale, bool calTime);
void Draw(Mat& img, vector<Rect>& faces, double scale);
// This function test if gpu_rst matches cpu_rst.
// If the two vectors are not equal, it will return the difference in vector size
// Else if will return (total diff of each cpu and gpu rects covered pixels)/(total cpu rects covered pixels)
double checkRectSimilarity(Size sz, std::vector<Rect>& cpu_rst, std::vector<Rect>& gpu_rst);
double checkRectSimilarity(Size sz, vector<Rect>& cpu_rst, vector<Rect>& gpu_rst);
int main( int argc, const char** argv )
{
const char* keys =
"{ h | help | false | print help message }"
"{ i | input | | specify input image }"
"{ t | template | ../../../data/haarcascades/haarcascade_frontalface_alt.xml | specify template file }"
"{ t | template | haarcascade_frontalface_alt.xml |"
" specify template file path }"
"{ c | scale | 1.0 | scale image }"
"{ s | use_cpu | false | use cpu or gpu to process the image }";
"{ s | use_cpu | false | use cpu or gpu to process the image }"
"{ o | output | facedetect_output.jpg |"
" specify output image save path(only works when input is images) }";
CommandLineParser cmd(argc, argv, keys);
if (cmd.get<bool>("help"))
......@@ -78,9 +87,10 @@ int main( int argc, const char** argv )
bool useCPU = cmd.get<bool>("s");
string inputName = cmd.get<string>("i");
outputName = cmd.get<string>("o");
string cascadeName = cmd.get<string>("t");
double scale = cmd.get<double>("c");
cv::ocl::OclCascadeClassifierBuf cascade;
ocl::OclCascadeClassifierBuf cascade;
CascadeClassifier cpu_cascade;
if( !cascade.load( cascadeName ) || !cpu_cascade.load(cascadeName) )
......@@ -114,9 +124,10 @@ int main( int argc, const char** argv )
return -1;
}
cvNamedWindow( "result", 1 );
std::vector<cv::ocl::Info> oclinfo;
int devnums = cv::ocl::getDevice(oclinfo);
vector<ocl::Info> oclinfo;
int devnums = ocl::getDevice(oclinfo);
if( devnums < 1 )
{
std::cout << "no device found\n";
......@@ -139,10 +150,12 @@ int main( int argc, const char** argv )
frame.copyTo( frameCopy );
else
flip( frame, frameCopy, 0 );
if(useCPU){
if(useCPU)
{
detectCPU(frameCopy, faces, cpu_cascade, scale, false);
}
else{
else
{
detect(frameCopy, faces, cascade, scale, false);
}
Draw(frameCopy, faces, scale);
......@@ -150,8 +163,10 @@ int main( int argc, const char** argv )
goto _cleanup_;
}
waitKey(0);
_cleanup_:
cvReleaseCapture( &capture );
}
......@@ -161,15 +176,18 @@ _cleanup_:
vector<Rect> faces;
vector<Rect> ref_rst;
double accuracy = 0.;
for(int i = 0; i <= LOOP_NUM;i ++)
for(int i = 0; i <= LOOP_NUM; i ++)
{
cout << "loop" << i << endl;
if(useCPU){
if(useCPU)
{
detectCPU(image, faces, cpu_cascade, scale, i==0?false:true);
}
else{
else
{
detect(image, faces, cascade, scale, i==0?false:true);
if(i == 0){
if(i == 0)
{
detectCPU(image, ref_rst, cpu_cascade, scale, false);
accuracy = checkRectSimilarity(image.size(), ref_rst, faces);
}
......@@ -189,31 +207,30 @@ _cleanup_:
}
cvDestroyWindow("result");
return 0;
}
void detect( Mat& img, vector<Rect>& faces,
cv::ocl::OclCascadeClassifierBuf& cascade,
double scale, bool calTime)
ocl::OclCascadeClassifierBuf& cascade,
double scale, bool calTime)
{
cv::ocl::oclMat image(img);
cv::ocl::oclMat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
ocl::oclMat image(img);
ocl::oclMat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
if(calTime) workBegin();
cv::ocl::cvtColor( image, gray, COLOR_BGR2GRAY );
cv::ocl::resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
cv::ocl::equalizeHist( smallImg, smallImg );
ocl::cvtColor( image, gray, COLOR_BGR2GRAY );
ocl::resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR );
ocl::equalizeHist( smallImg, smallImg );
cascade.detectMultiScale( smallImg, faces, 1.1,
3, 0
|CV_HAAR_SCALE_IMAGE
, Size(30,30), Size(0, 0) );
3, 0
|CV_HAAR_SCALE_IMAGE
, Size(30,30), Size(0, 0) );
if(calTime) workEnd();
}
void detectCPU( Mat& img, vector<Rect>& faces,
CascadeClassifier& cascade,
double scale, bool calTime)
CascadeClassifier& cascade,
double scale, bool calTime)
{
if(calTime) workBegin();
Mat cpu_gray, cpu_smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 );
......@@ -221,11 +238,12 @@ void detectCPU( Mat& img, vector<Rect>& faces,
resize(cpu_gray, cpu_smallImg, cpu_smallImg.size(), 0, 0, INTER_LINEAR);
equalizeHist(cpu_smallImg, cpu_smallImg);
cascade.detectMultiScale(cpu_smallImg, faces, 1.1,
3, 0 | CV_HAAR_SCALE_IMAGE,
Size(30, 30), Size(0, 0));
3, 0 | CV_HAAR_SCALE_IMAGE,
Size(30, 30), Size(0, 0));
if(calTime) workEnd();
}
void Draw(Mat& img, vector<Rect>& faces, double scale)
{
int i = 0;
......@@ -239,31 +257,38 @@ void Draw(Mat& img, vector<Rect>& faces, double scale)
radius = cvRound((r->width + r->height)*0.25*scale);
circle( img, center, radius, color, 3, 8, 0 );
}
cv::imshow( "result", img );
imshow( "result", img );
imwrite( outputName, img );
}
double checkRectSimilarity(Size sz, std::vector<Rect>& ob1, std::vector<Rect>& ob2)
double checkRectSimilarity(Size sz, vector<Rect>& ob1, vector<Rect>& ob2)
{
double final_test_result = 0.0;
size_t sz1 = ob1.size();
size_t sz2 = ob2.size();
if(sz1 != sz2)
{
return sz1 > sz2 ? (double)(sz1 - sz2) : (double)(sz2 - sz1);
}
else
{
cv::Mat cpu_result(sz, CV_8UC1);
if(sz1==0 && sz2==0)
return 0;
Mat cpu_result(sz, CV_8UC1);
cpu_result.setTo(0);
for(vector<Rect>::const_iterator r = ob1.begin(); r != ob1.end(); r++)
{
cv::Mat cpu_result_roi(cpu_result, *r);
Mat cpu_result_roi(cpu_result, *r);
cpu_result_roi.setTo(1);
cpu_result.copyTo(cpu_result);
}
int cpu_area = cv::countNonZero(cpu_result > 0);
int cpu_area = countNonZero(cpu_result > 0);
cv::Mat gpu_result(sz, CV_8UC1);
Mat gpu_result(sz, CV_8UC1);
gpu_result.setTo(0);
for(vector<Rect>::const_iterator r2 = ob2.begin(); r2 != ob2.end(); r2++)
{
......@@ -272,11 +297,13 @@ double checkRectSimilarity(Size sz, std::vector<Rect>& ob1, std::vector<Rect>& o
gpu_result.copyTo(gpu_result);
}
cv::Mat result_;
Mat result_;
multiply(cpu_result, gpu_result, result_);
int result = cv::countNonZero(result_ > 0);
final_test_result = 1.0 - (double)result/(double)cpu_area;
int result = countNonZero(result_ > 0);
if(cpu_area!=0 && result!=0)
final_test_result = 1.0 - (double)result/(double)cpu_area;
else if(cpu_area==0 && result!=0)
final_test_result = -1;
}
return final_test_result;
}
......
This diff is collapsed.
......@@ -12,19 +12,20 @@ using namespace cv;
using namespace cv::ocl;
typedef unsigned char uchar;
#define LOOP_NUM 10
#define LOOP_NUM 10
int64 work_begin = 0;
int64 work_end = 0;
static void workBegin()
{
static void workBegin()
{
work_begin = getTickCount();
}
static void workEnd()
{
work_end += (getTickCount() - work_begin);
}
static double getTime(){
static double getTime()
{
return work_end * 1000. / getTickFrequency();
}
......@@ -94,14 +95,15 @@ int main(int argc, const char* argv[])
//set this to save kernel compile time from second time you run
ocl::setBinpath("./");
const char* keys =
"{ help h | false | print help message }"
"{ left l | | specify left image }"
"{ right r | | specify right image }"
"{ camera c | 0 | enable camera capturing }"
"{ use_cpu s | false | use cpu or gpu to process the image }"
"{ video v | | use video as input }"
"{ points | 1000 | specify points count [GoodFeatureToTrack] }"
"{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }";
"{ help h | false | print help message }"
"{ left l | | specify left image }"
"{ right r | | specify right image }"
"{ camera c | 0 | enable camera capturing }"
"{ use_cpu s | false | use cpu or gpu to process the image }"
"{ video v | | use video as input }"
"{ output o | pyrlk_output.jpg| specify output save path when input is images }"
"{ points | 1000 | specify points count [GoodFeatureToTrack] }"
"{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }";
CommandLineParser cmd(argc, argv, keys);
......@@ -115,10 +117,10 @@ int main(int argc, const char* argv[])
string fname0 = cmd.get<string>("left");
string fname1 = cmd.get<string>("right");
string vdofile = cmd.get<string>("video");
string outfile = cmd.get<string>("output");
int points = cmd.get<int>("points");
double minDist = cmd.get<double>("min_dist");
bool useCPU = cmd.has("s");
bool useCamera = cmd.has("c");
int inputName = cmd.get<int>("c");
oclMat d_nextPts, d_status;
......@@ -131,21 +133,9 @@ int main(int argc, const char* argv[])
vector<unsigned char> status(points);
vector<float> err;
if (frame0.empty() || frame1.empty())
{
useCamera = true;
defaultPicturesFail = true;
VideoCapture capture(inputName);
if (!capture.isOpened())
{
cout << "Can't load input images" << endl;
return -1;
}
}
cout << "Points count : " << points << endl << endl;
if (useCamera)
if (frame0.empty() || frame1.empty())
{
VideoCapture capture;
Mat frame, frameCopy;
......@@ -238,10 +228,10 @@ _cleanup_:
else
{
nocamera:
for(int i = 0; i <= LOOP_NUM;i ++)
for(int i = 0; i <= LOOP_NUM; i ++)
{
cout << "loop" << i << endl;
if (i > 0) workBegin();
if (i > 0) workBegin();
if (useCPU)
{
......@@ -271,8 +261,8 @@ nocamera:
cout << getTime() / LOOP_NUM << " ms" << endl;
drawArrows(frame0, pts, nextPts, status, Scalar(255, 0, 0));
imshow("PyrLK [Sparse]", frame0);
imwrite(outfile, frame0);
}
}
}
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment