c++ including <complex> causes a syntax error in file string - string

Error 3 error C2059: syntax error : ')' c:\program files\microsoft visual studio 10.0\vc\include\string 758 1 ECE572_001_Project1_swirl
Error 6 error C2059: syntax error : ')' c:\program files\microsoft visual studio 10.0\vc\include\string 767 1 ECE572_001_Project1_swirl
Error 1 error C2143: syntax error : missing ')' before 'string' c:\program files\microsoft visual studio 10.0\vc\include\string 758 1 ECE572_001_Project1_swirl
Error 4 error C2143: syntax error : missing ')' before 'string' c:\program files\microsoft visual studio 10.0\vc\include\string 767 1 ECE572_001_Project1_swirl
Error 2 error C2665: 'swprintf' : none of the 2 overloads could convert all the argument types c:\program files\microsoft visual studio 10.0\vc\include\string 758 1 ECE572_001_Project1_swirl
Error 5 error C2665: 'swprintf' : none of the 2 overloads could convert all the argument types c:\program files\microsoft visual studio 10.0\vc\include\string 767 1 ECE572_001_Project1_swirl
I don't understand this error, because it says the error is in the file string, which is a locked file provided by VS2010. Second, I'm not even using string, and third, how could including complex have anything to do with the library string?
Even though including complex causes the error in my project file, I started a whole new file to test including it, and the error didn't happen there.
#include "Image.h"
#include <iostream>
#include <complex>
using namespace std;
#define Usage "makeSwirl inImg outImg coeff\n"
/*
* arg1 is the image to transform.
* arg2 is the swirl coefficient
* Returns image with enhanced edges.
*/
Image swirl(const Image&, const float&);
/*
* arg1 is the image within which the pixel to be transformed is located.
* arg2&3&4 are the row, colum, and channel of the pixel to transform.
* arg5 is the swirl coefficient
* arg6&7 are the rows and cols of arg1.
* returns transformed pixel.
*/
float onePixelSwirl(const Image&, const int&, const int&, const int&, const double&, const int&, const int&);
int main(int argc, char **argv)
{
// Check for proper number of arguments.
if(argc != 4)
{
cout << Usage;
exit(3);
}
// Read in image specified by user.
const Image IN_IMG = readImage(argv[1]);
// Create output image with oil effect.
Image outImg = swirl(IN_IMG, atof(argv[3]));
// Output the image
writeImage(outImg, argv[2]);
// Success!
return(0);
}
Image swirl(const Image& IN_IMG, const float& COEFF)
{
Image outImg;
// Allocate memory
const int ROWS = IN_IMG.getRow();
const int COLS = IN_IMG.getCol();
const int CHANNELS = IN_IMG.getChannel();
outImg.createImage(ROWS, COLS, IN_IMG.getType());
// Perform edge effect
for (int k = 0; k < CHANNELS; ++k)
for (int i = 0; i < ROWS; ++i)
for (int j = 0; j < COLS; ++j)
outImg(i,j,k) = onePixelSwirl(IN_IMG, i, j, k, COEFF, ROWS, COLS);
return outImg;
}
float onePixelSwirl(const Image& IN_IMG, const int& ROW, const int& COL,
const int& CHANNEL, const double& COEFF, const int& ROWS, const int& COLS)
{
// define shift of origin
//const double X_SHIFT = ROWS/2.0;
//const double Y_SHIFT = COLS/2.0;
//const complex<double> NEW_SHIFTED(ROW - X_SHIFT, COL - Y_SHIFT);
//const double r = abs(NEW_SHIFTED);
//const complex<double> OLD_SHIFTED = polar(r, arg(NEW_SHIFTED) + r/COEFF);
//const int OLD_ROW = OLD_SHIFTED.real() <= ROWS ? OLD_SHIFTED.real() : ROWS;
//const int OLD_COL = OLD_SHIFTED.imag() <= COLS ? OLD_SHIFTED.imag() : COLS;
//return IN_IMG(OLD_ROW, OLD_COL, CHANNEL);
return 0;
}
I put the include statement above including image.h, and the compilation bugs vanished. Here is image.h if someone could figure out the problem:
/********************************************************************
* Image.h - header file of the Image library which defines
* a new class "Image" and the associated member functions
*
* Author: Hairong Qi, hqi#utk.edu, ECE, University of Tennessee
*
* Created: 02/05/02
*
* Note:
* This is a simple C++ library for image processing.
* The purpose is not high performance, but to show how
* the algorithm works through programming.
* This library can only read in PGM/PPM format images.
*
* Modification:
* 07/31/09 - moving header files for colorProcessing, imageIO, and
* matrixProcessing to this file
* 01/22/06 - reorganize the Image library such that the Image class
* only contains member functions related to the most
* fundamental image operation
* 11/12/05 - add wavelet transform function
* 09/26/05 - add Fourier transform related functions
* 09/07/05 - add overloading function for "/"
* 09/07/05 - modify createImage() function
* 09/07/05 - fix problems with copy constructor
* 08/07/05 - regrouping functions
********************************************************************/
#ifndef IMAGE_H
#define IMAGE_H
#include <iostream>
#include <cmath>
using namespace std;
#define PGMRAW 1 // magic number is 'P5'
#define PPMRAW 2 // magic number is 'P6'
#define PGMASCII 3 // magic number is 'P2'
#define PPMASCII 4 // magic number is 'P3'
#define GRAY 10 // gray-level image
#define BINARY 11 // binary image
#define NBIT 8
#define L ( pow(2.0,NBIT)-1 ) // the largest intensity represented by NBIT
class Image {
friend ostream & operator<<(ostream &, Image &);
friend Image operator/(Image &, double); // image divided by a scalar
friend Image operator*(Image &, double); // image multiplied by a scalar
friend Image operator+(Image &, double); // image add a scalar
friend Image operator-(Image &, double); // image subtract a scalar
public:
// constructors and destructor
Image(); // default constructor
Image(int, // constructor with row
int, // column
int t=PGMRAW); // type (use PGMRAW, PPMRAW,
// PGMASCII, PPMASCII)
Image(const Image &); // copy constructor
~Image(); // destructor
// create an image
void createImage(); // create an image, parameters all set
void createImage(int, // create an image with row
int c=1, // column (default 1, a column vector)
int t=PGMRAW); // and type, default is PGMRAW
void initImage(float init=0.0); // initiate the pixel value of an img
// the default is 0.0
// get and set functions
int getRow() const; // get row # / the height of the img
int getCol() const; // get col # / the width of the image
int getChannel() const; // get channel number of the image
int getType() const; // get the image type
float getMaximum() const; // get the maximum pixel value
void getMaximum(float &, // return the maximum pixel value
int &, int &); // and its indices
float getMinimum() const; // get the mininum pixel value
void getMinimum(float &, // return the minimum pixel value
int &, int &); // and its indices
Image getRed() const; // get the red channel
Image getGreen() const; // get the green channel
Image getBlue() const; // get the blue channel
Image getImage(int) const; // get the kth channel image,
// k starts at 0
void setRow(int); // set row number
void setCol(int); // set column number
void setChannel(int); // set the number of channel
void setType(int t=PGMRAW); // set the image type
void setRed(Image &); // set the red channel
void setGreen(Image &); // set the green channel
void setBlue(Image &); // set the blue channel
void setImage(Image &, int); // set the kth channel image,
// k starts at 0
// operator overloading functions
float & operator()(int, // operator overloading (i,j,k)
int c = 0, // when c=k=0, a column vector
int k = 0) const;
const Image operator=(const Image &); // = operator overloading
Image operator+(const Image &) const; // overloading + operator
Image operator-(const Image &) const; // overloading - operator
Image operator*(const Image &) const; // overloading pixelwise *
Image operator/(const Image &) const; // overloading pixelwise division
Image operator->*(const Image &) const; // overloading ->* operator
// (matrix multiplication)
bool IsEmpty() const { return (image==NULL); }
private:
int row; // number of rows / height
int col; // number of columns / width
int channel; // nr of channels (1 for gray, 3 for color)
int type; // image type (PGM, PPM, etc.)
int maximum; // the maximum pixel value
float *image; // image buffer
};
////////////////////////////////////
// image I/O
Image readImage(char *); // read image
void writeImage(Image &, // write an image
char *,
int flag=0); // flag for rescale, rescale when == 1
Image rescale(Image &, // rescale an image
float a=0.0, // lower bound
float b=L); // upper bound
////////////////////////////////////
// color processing routines
Image RGB2HSI(Image &); // convert from RGB to HSI model
Image HSI2RGB(Image &); // convert from HSI to RGB model
////////////////////////////////////
// matrix manipulation
Image transpose(Image &); // image transpose
Image inverse(Image &); // image inverse
Image pinv(Image &); // image pseudo-inverse
Image subImage(Image &, // crop an image
int, // starting row index
int, // starting column index
int, // ending row index
int); // ending column index
#endif

There's a number of things that are suspicious but the main one is the definition of L. If I recall, L is used to indicate a Unicode string literal as in L"Some Unicode text". It seems likely that <complex> uses this. By including Image.h before <complex>, you've redefined it. This would also explain the broken calls to swprintf().
Since you don't use L in Image.h is there any reason to declare it there? If L is part of the interface and actually needs to be in the header file, consider renaming it to something less likely to provoke a name conflict.
Other things that look suspicious but aren't necessarily the problem here: You've included <cmath> in Image.h for no apparent reason. Generally, you should only include the files you actually need. A bigger issue is the using namespace std in the header. This is almost always a bad idea since it pulls every name in the std namespace into the local scope of every file that includes this header file. It greatly increases the chance of name collisions that could be tricky to sort out (as you can see)

Related

Why can't I render onto a Skia canvas holding a 8 bit Grayscale bitmap

I am trying to do some basic drawing with skia. Since I'm working on grayscale images I want to use the corresponding color type. The minimal Example I want to use is:
int main(int argc, char * const argv[])
{
int width = 1000;
int heigth = 1000;
float linewidth = 10.0f;
SkImageInfo info = SkImageInfo::Make(
width,
heigth,
SkColorType::kAlpha_8_SkColorType,
SkAlphaType::kPremul_SkAlphaType
);
SkBitmap img;
img.allocPixels(info);
SkCanvas canvas(img);
canvas.drawColor(SK_ColorBLACK);
SkPaint paint;
paint.setColor(SK_ColorWHITE);
paint.setAlpha(255);
paint.setAntiAlias(false);
paint.setStrokeWidth(linewidth);
paint.setStyle(SkPaint::kStroke_Style);
canvas.drawCircle(500.0f, 500.0f, 100.0f, paint);
bool success = SkImageEncoder::EncodeFile("B:\\img.png", img,
SkImageEncoder::kPNG_Type, 100);
return 0;
}
But the saved image does not contain the circle that was drawn. If I replace kAlpha_8_SkColorType with kN32_SkColorType I get the expected result. How can I draw the circle onto a 8 bit grayscale image? I'm working with Visual Studio 2013 on a 64bit Windows machine.
kN32_SkColorType type result
kAlpha_8_SkColorType result
You should use kGray_8_SkColorType than kAlpha_8_SkColorType.
The kAlpha_8_SkColorType used for bitmap mask.

CUDA Programming: Compilation Error

I am making a CUDA program that implements the data parallel prefix sum calculation operating upon N numbers. My code is also supposed to generate the numbers on the host using a random number generator. However, I seem to always run into a "unrecognized token" and "expected a declaration" error on the ending bracket of int main when attempting to compile. I am running the code on Linux.
#include <stdio.h>
#include <cuda.h>
#include <stdlib.h>
#include <math.h>
__global__ void gpu_cal(int *a,int i, int n) {
int tid = blockIdx.x * blockDim.x + threadIdx.x;
if(tid>=i && tid < n) {
a[tid] = a[tid]+a[tid-i];
}
}
int main(void)
{
int key;
int *dev_a;
int N=10;//size of 1D array
int B=1;//blocks in the grid
int T=10;//threads in a block
do{
printf ("Some limitations:\n");
printf (" Maximum number of threads per block = 1024\n");
printf (" Maximum sizes of x-dimension of thread block = 1024\n");
printf (" Maximum size of each dimension of grid of thread blocks = 65535\n");
printf (" N<=B*T\n");
do{
printf("Enter size of array in one dimension, currently %d\n",N);
scanf("%d",&N);
printf("Enter size of blocks in the grid, currently %d\n",B);
scanf("%d",&B);
printf("Enter size of threads in a block, currently %d\n",T);
scanf("%d",&T);
if(N>B*T)
printf("N>B*T, this will result in an incorrect result generated by GPU, please try again\n");
if(T>1024)
printf("T>1024, this will result in an incorrect result generated by GPU, please try again\n");
}while((N>B*T)||(T>1024));
cudaEvent_t start, stop; // using cuda events to measure time
float elapsed_time_ms1, elapsed_time_ms3;
int a[N],gpu_result[N];//for result generated by GPU
int cpu_result[N];//CPU result
cudaMalloc((void**)&dev_a,N * sizeof(int));//allocate memory on GPU
int i,j;
srand(1); //initialize random number generator
for (i=0; i < N; i++) // load array with some numbers
a[i] = (int)rand() ;
cudaMemcpy(dev_a, a , N*sizeof(int),cudaMemcpyHostToDevice);//load data from host to device
cudaEventCreate(&start); // instrument code to measure start time
cudaEventCreate(&stop);
cudaEventRecord(start, 0);
//GPU computation
for(j=0;j<log(N)/log(2);j++){
gpu_cal<<<B,T>>>(dev_a,pow(2,j),N);
cudaThreadSynchronize();
}
cudaMemcpy(gpu_result,dev_a,N*sizeof(int),cudaMemcpyDeviceToHost);
cudaEventRecord(stop, 0); // instrument code to measue end time
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsed_time_ms1, start, stop );
printf("\n\n\nTime to calculate results on GPU: %f ms.\n", elapsed_time_ms1); // print out execution time
//CPU computation
cudaEventRecord(start, 0);
for(i=0;i<N;i++)
{
cpu_result[i]=0;
for(j=0;j<=i;j++)
{
cpu_result[i]=cpu_result[i]+a[j];
}
}
cudaEventRecord(stop, 0); // instrument code to measue end time
cudaEventSynchronize(stop);
cudaEventElapsedTime(&elapsed_time_ms3, start, stop );
printf("Time to calculate results on CPU: %f ms.\n\n", elapsed_time_ms3); // print out execution time
//Error check
for(i=0;i < N;i++) {
if (gpu_result[i] != cpu_result[i] ) {
printf("ERROR!!! CPU and GPU create different answers\n");
break;
}
}
//Calculate speedup
printf("Speedup on GPU compared to CPU= %f\n", (float) elapsed_time_ms3 / (float) elapsed_time_ms1);
printf("\nN=%d",N);
printf("\nB=%d",B);
printf("\nT=%d",T);
printf("\n\n\nEnter '1' to repeat, or other integer to terminate\n");
scanf("%d",&key);
}while(key == 1);
cudaFree(dev_a);//deallocation
return 0;
}​
The very last } in your code is a Unicode character. If you delete this entire line, and retype the }, the error will be gone.
There are two compile errors in your code.
First, Last ending bracket is a unicode character, so you should resave your code as unicode or delete and rewrite the last ending bracket.
Second, int type variable N which used at this line - int a[N],gpu_result[N];//for result generated by GPU
was declared int type, but it's not allowed in c or c++ compiler, so you should change the N declaration as const int N.

lsmod showing module is used by -2

I am trying to pass command line parameters using following code
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/moduleparam.h>
static int nilvar=0;
static int nilvar2=0;
int rollcalls[5];// = {0};
char classname[10];// = "math";
module_param_named (var,nilvar2,int,0644);
module_param (nilvar,int,0644);
module_param_array_named(present,rollcalls,int,5,0644);
module_param_string(subject,classname,10,0644);
int init_module(void)
{
printk(KERN_INFO"1) nilvar = %d\n 2) nilvar2 = %d",nilvar,nilvar2);
printk(KERN_INFO/*NOTICE*/"ROLLCALLS = %d ,%d ,%d ,%d",rollcalls[0],rollcalls[1],rollcalls[2],rollcalls[3]);
printk(KERN_INFO/*DEBUG*/"classname = %s",classname);
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Bye....\n");
}
MODULE_LICENSE("GPL");
after make ,I am passing my arguments by
insmod module1.ko var=5 nilvar=6 present=1 2 3 4 subject=physics
I don't know exactly what is happening but now lsmod shows module used by -2.
(actually no module is dependent on this module)
so where I am wrong ? and if we want to modify all this variables as a structure elements, then how to use module_param() macro for it?
#user3452214, instead of module_param_array_named(present, rollcalls, int, **5**, 0644); use module_param_array_named(present, rollcalls, int, **&count**, 0644); added one more variable i.e. static unsigned int count which keep count of the number written to the array. We need to pass the pointer as explained in the moduleparam.h, thus cannot pass numerical value for this parameter. It works fine!!!. Hope it solves your problem.
/**
* module_param_array_named - renamed parameter which is an array of some type
* #name: a valid C identifier which is the parameter name
* #array: the name of the array variable
* #type: the type, as per module_param()
* #nump: optional pointer filled in with the number written
* #perm: visibility in sysfs
*
* This exposes a different name than the actual variable name. See
* module_param_named() for why this might be necessary.
*/
#define module_param_array_named(name, array, type, nump, perm)

cvFindContours always returns 0 - OpenCV

I'm calling the cvFindContours function inside a separate thread that I've created to handle all OpenCV work while another is kept for OpenGL stuff.
I noticed that my cvFindContours function always returns 0 when this code is executed inside a separate thread. It worked fine before, when executed in the main thread itself. I used breakpoints and Watches to evaluate value changes. everything else (variables) gets values except for contourCount (value: 0).
Any clue?
// header includes goes here
CvCapture* capture = NULL;
IplImage* frame = NULL;
IplImage* image;
IplImage* gray;
IplImage* grayContour;
CvMemStorage *storage;
CvSeq *firstcontour=NULL;
CvSeq *polycontour=NULL;
int contourCount = 0;
DWORD WINAPI startOCV(LPVOID vpParam){
capture = cvCaptureFromCAM(0); // NOTE 1
capture = cvCaptureFromCAM(0);
frame = cvQueryFrame(capture);
image = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U,3);
gray = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U,1);
grayContour = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U,1);
storage = cvCreateMemStorage (0);
firstcontour=NULL;
while(1){
frame = cvQueryFrame(capture);
cvCopy(frame,image);
cvCvtColor(image,gray,CV_BGR2GRAY);
cvSmooth(gray,gray,CV_GAUSSIAN,3);
cvThreshold (gray, gray, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
cvNot(gray,gray);
cvCopy(gray,grayContour);
contourCount=cvFindContours (grayContour, storage, &firstcontour, sizeof (CvContour),
CV_RETR_CCOMP);
polycontour=cvApproxPoly(firstcontour,sizeof(CvContour),storagepoly,CV_POLY_APPROX_DP,3,1); // Error starts here (Pls refer to stack trace)
}
// goes on...
}
int main(int argc, char** argv){
DWORD qThreadID;
HANDLE ocvThread = CreateThread(0,0,startOCV, NULL,0, &qThreadID);
initGL(argc, argv); //some GL intitialization functions
glutMainLoop(); // draw some 3D objects
CloseHandle(ocvThread);
return 0;
}
NOTE1: these lines had to be duplicated due to the error mentioned at How to avoid "Video Source -> Capture source" selection in OpenCV 2.3.0 - Visual C++ 2008
Environment:
OpenCV 2.3.0
Visual C++ 2008
EDIT
Traces
opencv_core230d.dll!cv::error(const cv::Exception & exc={...}) Line 431 C++
opencv_imgproc230d.dll!cvPointSeqFromMat(int seq_kind=20480, const void * arr=0x00000000, CvContour * contour_header=0x01a6f514, CvSeqBlock * block=0x01a6f4f4) Line 47 + 0xbd bytes C++
opencv_imgproc230d.dll!cvApproxPoly(const void * array=0x00000000, int header_size=88, CvMemStorage * storage=0x017e7b40, int method=0, double parameter=3.0000000000000000, int parameter2=1) Line 703 + 0x28 bytes C++
Project.exe!startOCV(void * vpParam=0x00000000) Line 267 + 0x24 bytes C++
All this stuff boils down to the function CV_Assert( arr != 0 && contour_header != 0 && block != 0 ) in cvPointSeqFromMat and it fails since arr it requires is empty.
Your variable contourCount is not doing what you think it's doing. From the contours.cpp source file:
/*F///////////////////////////////////////////////////////////////////////////////////////
// Name: cvFindContours
// Purpose:
// Finds all the contours on the bi-level image.
// Context:
// Parameters:
// img - source image.
// Non-zero pixels are considered as 1-pixels
// and zero pixels as 0-pixels.
// step - full width of source image in bytes.
// size - width and height of the image in pixels
// storage - pointer to storage where will the output contours be placed.
// header_size - header size of resulting contours
// mode - mode of contour retrieval.
// method - method of approximation that is applied to contours
// first_contour - pointer to first contour pointer
// Returns:
// CV_OK or error code
// Notes:
//F*/
You are getting CV_OK == 0, which means it successfully ran. cvFindContours does not return the number of contours found to you. It merely lets you known if it failed or not. You should use the CvSeq* first_contour to figure out the number of contours detected.
Hope that helps!

How to get a String^ into a 2d char array?

I'm trying to copy characters from a System::String ^ to a rectangular char array.
First I tried: (along with some other code. not relevant to the question)
char name[25][21];
...
void savedata(int x, System::String ^ a){ //x is the student #, a is the name
int b;
using namespace System::Runtime::InteropServices; // for class Marshal
char* buffer((char*)(void*)Marshal::StringToHGlobalAnsi(a));
x--; //So we write buffer[b] at data[0][b] when int x is 1
for(b = 0; b < 21; b++){
data[x][b] = buffer[b];
};
}
and when I tried to run and debug it, "An unhandled exception of type 'System.AccessViolationException'" occurred
Is there some easier/better way to put a String^ into a (2 dimensional) char array, and if not, what am I doing wrong here?
You should be calling .ToPointer() to convert the result of StringToHGlobalAnsi to something that you can then cast to char*.
You should also call FreeHGlobal on the result of StringToHGlobalAnsi (or you can recreate an IntPtr from your char*).

Resources