Search Results

Search found 233 results on 10 pages for 'mat banik'.

Page 1/10 | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • OpenGL - Frustum not culling polygons beyond far plane

    - by Pladnius Brooks
    I have implemented frustum culling and am checking the bounding box for its intersection with the frustum planes. I added the ability to pause frustum updates which lets me see if the frustum culling has been working correctly. When I turn around after I have paused it, nothing renders behind me and to the left and right side, they taper off as well just as you would expect. Beyond the clip distance (far plane), they still render and I am not sure whether it is a problem with my frustum updating or bounding box checking code or I am using the wrong matrix or what. As I put the distance in the projection matrix at 3000.0f, it still says that bounding boxes well past that are still in the frustum, which isn't the case. Here is where I create my modelview matrix: projectionMatrix = glm::perspective(newFOV, 4.0f / 3.0f, 0.1f, 3000.0f); viewMatrix = glm::mat4(1.0); viewMatrix = glm::scale(viewMatrix, glm::vec3(1.0, 1.0, -1.0)); viewMatrix = glm::rotate(viewMatrix, anglePitch, glm::vec3(1.0, 0.0, 0.0)); viewMatrix = glm::rotate(viewMatrix, angleYaw, glm::vec3(0.0, 1.0, 0.0)); viewMatrix = glm::translate(viewMatrix, glm::vec3(-x, -y, -z)); modelViewProjectiomMatrix = projectionMatrix * viewMatrix; The reason I scale it by -1 in the Z direction is because the levels were designed to be rendered with DirectX so I reverse the Z direction. Here is where I update my frustum: void CFrustum::calculateFrustum() { glm::mat4 mat = camera.getModelViewProjectionMatrix(); // Calculate the LEFT side m_Frustum[LEFT][A] = (mat[0][3]) + (mat[0][0]); m_Frustum[LEFT][B] = (mat[1][3]) + (mat[1][0]); m_Frustum[LEFT][C] = (mat[2][3]) + (mat[2][0]); m_Frustum[LEFT][D] = (mat[3][3]) + (mat[3][0]); // Calculate the RIGHT side m_Frustum[RIGHT][A] = (mat[0][3]) - (mat[0][0]); m_Frustum[RIGHT][B] = (mat[1][3]) - (mat[1][0]); m_Frustum[RIGHT][C] = (mat[2][3]) - (mat[2][0]); m_Frustum[RIGHT][D] = (mat[3][3]) - (mat[3][0]); // Calculate the TOP side m_Frustum[TOP][A] = (mat[0][3]) - (mat[0][1]); m_Frustum[TOP][B] = (mat[1][3]) - (mat[1][1]); m_Frustum[TOP][C] = (mat[2][3]) - (mat[2][1]); m_Frustum[TOP][D] = (mat[3][3]) - (mat[3][1]); // Calculate the BOTTOM side m_Frustum[BOTTOM][A] = (mat[0][3]) + (mat[0][1]); m_Frustum[BOTTOM][B] = (mat[1][3]) + (mat[1][1]); m_Frustum[BOTTOM][C] = (mat[2][3]) + (mat[2][1]); m_Frustum[BOTTOM][D] = (mat[3][3]) + (mat[3][1]); // Calculate the FRONT side m_Frustum[FRONT][A] = (mat[0][3]) + (mat[0][2]); m_Frustum[FRONT][B] = (mat[1][3]) + (mat[1][2]); m_Frustum[FRONT][C] = (mat[2][3]) + (mat[2][2]); m_Frustum[FRONT][D] = (mat[3][3]) + (mat[3][2]); // Calculate the BACK side m_Frustum[BACK][A] = (mat[0][3]) - (mat[0][2]); m_Frustum[BACK][B] = (mat[1][3]) - (mat[1][2]); m_Frustum[BACK][C] = (mat[2][3]) - (mat[2][2]); m_Frustum[BACK][D] = (mat[3][3]) - (mat[3][2]); // Normalize all the sides NormalizePlane(m_Frustum, LEFT); NormalizePlane(m_Frustum, RIGHT); NormalizePlane(m_Frustum, TOP); NormalizePlane(m_Frustum, BOTTOM); NormalizePlane(m_Frustum, FRONT); NormalizePlane(m_Frustum, BACK); } And finally, where I check the bounding box: bool CFrustum::BoxInFrustum( float x, float y, float z, float x2, float y2, float z2) { // Go through all of the corners of the box and check then again each plane // in the frustum. If all of them are behind one of the planes, then it most // like is not in the frustum. for(int i = 0; i < 6; i++ ) { if(m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x2 + m_Frustum[i][B] * y + m_Frustum[i][C] * z + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x + m_Frustum[i][B] * y2 + m_Frustum[i][C] * z + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x2 + m_Frustum[i][B] * y2 + m_Frustum[i][C] * z + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x + m_Frustum[i][B] * y + m_Frustum[i][C] * z2 + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x2 + m_Frustum[i][B] * y + m_Frustum[i][C] * z2 + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x + m_Frustum[i][B] * y2 + m_Frustum[i][C] * z2 + m_Frustum[i][D] > 0) continue; if(m_Frustum[i][A] * x2 + m_Frustum[i][B] * y2 + m_Frustum[i][C] * z2 + m_Frustum[i][D] > 0) continue; // If we get here, it isn't in the frustum return false; } // Return a true for the box being inside of the frustum return true; }

    Read the article

  • OpenCV Mat creation memory leak

    - by Royi Freifeld
    My memory is getting full fairly quick once using the next piece of code. Valgrind shows a memory leak, but everything is allocated on stack and (supposed to be) freed once the function ends. void mult_run_time(int rows, int cols) { Mat matrix(rows,cols,CV_32SC1); Mat row_vec(cols,1,CV_32SC1); /* initialize vector and matrix */ for (int col = 0; col < cols; ++col) { for (int row = 0; row < rows; ++row) { matrix.at<unsigned long>(row,col) = rand() % ULONG_MAX; } row_vec.at<unsigned long>(1,col) = rand() % ULONG_MAX; } /* end initialization of vector and matrix*/ matrix*row_vec; } int main() { for (int row = 0; row < 20; ++row) { for (int col = 0; col < 20; ++col) { mult_run_time(row,col); } } return 0; } Valgrind shows that there is a memory leak in line Mat row_vec(cols,1,CV_32CS1): ==9201== 24,320 bytes in 380 blocks are definitely lost in loss record 50 of 50 ==9201== at 0x4026864: malloc (vg_replace_malloc.c:236) ==9201== by 0x40C0A8B: cv::fastMalloc(unsigned int) (in /usr/local/lib/libopencv_core.so.2.3.1) ==9201== by 0x41914E3: cv::Mat::create(int, int const*, int) (in /usr/local/lib/libopencv_core.so.2.3.1) ==9201== by 0x8048BE4: cv::Mat::create(int, int, int) (mat.hpp:368) ==9201== by 0x8048B2A: cv::Mat::Mat(int, int, int) (mat.hpp:68) ==9201== by 0x80488B0: mult_run_time(int, int) (mat_by_vec_mult.cpp:26) ==9201== by 0x80489F5: main (mat_by_vec_mult.cpp:59) Is it a known bug in OpenCV or am I missing something?

    Read the article

  • How to convert a Mat variable type in an IplImage variable type in OpenCV 2.0 ?

    - by user290613
    Hi all, I am trying to rotate an image in OpenCV. I've used this code that I found here on StackOverflow Mat source(img); Point2f src_center(source.cols/2.0, source.rows/2.0); Mat rot_mat = getRotationMatrix2D(src_center, 40.0, 1.0); Mat dst; warpAffine(source, dst, rot_mat, source.size()); Once I have my dst Mat variable type filled up I would like to put it back to an IplImage variable type, any idea about how to do this ? Thank you,

    Read the article

  • loading multiple .mat files in MATLAB

    - by smilingbuddha
    I have 110 files named time1.mat, time2.mat ..., time110.mat. I want to load these matrices into the MATLAB workspace. I have always used load -'ASCII' matrix.mat to load an ASCII matrix file in the current folder. So I tried doing for i=1:10 filename=strcat('time',int2str(i),'.mat'); load -'ASCII' filename end But I am getting a MATLAB error as ??? Error using ==> load Unable to read file filename: No such file or directory. ? Of course the string filename seems to be evaluated correctly by MATLAB as time1.mat. in the first iteration where it crashes at the load line. Any suggestions how I should do this?

    Read the article

  • Write a MAT file without using matlab headers and libraries.

    - by YuppieNetworking
    Hello all, I have some data that I would like to save to a MAT file (version 4 or 5, or any version, for that matter). The catch: I wanted to do this without using matlab libraries, since this code will not necessary run in a machine with matlab. My program uses Java and C++, so any existing library in those languages that achieves this could help me out... I did some research but did not find anything in Java/C++. However, I found that scipy on python achieves this with mio4.py or mio5.py. I thought about implementing this on java or C++, but it seems a bit out of my time schedule. So the question is: is there any libraries in Java or C/C++ that permits saving MAT files without using Matlab libraries? Thanks a lot

    Read the article

  • Converting cv::Mat to IplImage*

    - by amr
    The documentation on this seems incredibly spotty. I've basically got an empty array of IplImage*s (IplImage** imageArray) and I'm calling a function to import an array of cv::Mats - I want to convert my cv::Mat into an IplImage* so I can copy it into the array. Currently I'm trying this: while(loop over cv::Mat array) { IplImage* xyz = &(IplImage(array[i])); cvCopy(iplimagearray[i], xyz); } Which generates a segfault. Also trying: while(loop over cv::Mat array) { IplImage* xyz; xyz = &array[i]; cvCopy(iplimagearray[i], xyz); } Which gives me a compile time error of: error: cannot convert ‘cv::Mat*’ to ‘IplImage*’ in assignment Stuck as to how I can go further and would appreciate some advice :)

    Read the article

  • Mat matrix multiplication, openCV?

    - by facebook-1593205594
    I initialized two Mat images as: Mat ft=Mat::zeros(src.rows,src.cols,CV_32FC1),h=Mat::zeros(src.rows,src.cols,CV_32FC1); and then i have some calculations: ft has fourier transform stored for an image, and h has matrix for Laplacian filtering in fourier domain.......they both have same dimensions, and then i did multiplication of them using both h*ft and gemm(h,ft,1,NULL,0,temp); function call but while executing it shows some problems..... it reads like this: opencv error assertion failed (some long code and at last says something about gemm in ....matmul.cpp)......termination called after throwing exception of 'cv::exception'

    Read the article

  • Openvpn mat through access server depending on client

    - by Lucas Kauffman
    I have several services which should be accessible through a VPN. Clients who connect through the VPN server should be NATed so that all their traffic passes through the access server. However server residing on the network should not pass their traffic through the access server their VPN facing services should be accessible, but their internet connections should not pas through the access server. So how can I enable NAT on a per client basis using OpenVPN?

    Read the article

  • backtracking in haskell

    - by dmindreader
    I have to traverse a matrix and say how many "characteristic areas" of each type it has. A characteristic area is defined as a zone where elements of value n or n are adjacent. For example, given the matrix: 0 1 2 2 0 1 1 2 0 3 0 0 There's a single characteristic area of type 1 which is equal to the original matrix: 0 1 2 2 0 1 1 2 0 3 0 0 There are two characteristic areas of type 2: 0 0 2 2 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 3 0 0 And one characteristic area of type 3: 0 0 0 0 0 0 0 0 0 3 0 0 So, for the function call: countAreas [[0,1,2,2],[0,1,1,2],[0,3,0,0]] The result should be [1,2,1] I haven't defined countAreas yet, I'm stuck with my visit function when it has no more possible squares in which to move it gets stuck and doesn't make the proper recursive call. I'm new to functional programming and I'm still scratching my head about how to implement a backtracking algorithm here. Take a look at my code, what can I do to change it? move_right :: (Int,Int) -> [[Int]] -> Int -> Bool move_right (i,j) mat cond | (j + 1) < number_of_columns mat && consult (i,j+1) mat /= cond = True | otherwise = False move_left :: (Int,Int) -> [[Int]] -> Int -> Bool move_left (i,j) mat cond | (j - 1) >= 0 && consult (i,j-1) mat /= cond = True | otherwise = False move_up :: (Int,Int) -> [[Int]] -> Int -> Bool move_up (i,j) mat cond | (i - 1) >= 0 && consult (i-1,j) mat /= cond = True | otherwise = False move_down :: (Int,Int) -> [[Int]] -> Int -> Bool move_down (i,j) mat cond | (i + 1) < number_of_rows mat && consult (i+1,j) mat /= cond = True | otherwise = False imp :: (Int,Int) -> Int imp (i,j) = i number_of_rows :: [[Int]] -> Int number_of_rows i = length i number_of_columns :: [[Int]] -> Int number_of_columns (x:xs) = length x consult :: (Int,Int) -> [[Int]] -> Int consult (i,j) l = (l !! i) !! j visited :: (Int,Int) -> [(Int,Int)] -> Bool visited x y = elem x y add :: (Int,Int) -> [(Int,Int)] -> [(Int,Int)] add x y = x:y visit :: (Int,Int) -> [(Int,Int)] -> [[Int]] -> Int -> [(Int,Int)] visit (i,j) vis mat cond | move_right (i,j) mat cond && not (visited (i,j+1) vis) = visit (i,j+1) (add (i,j+1) vis) mat cond | move_down (i,j) mat cond && not (visited (i+1,j) vis) = visit (i+1,j) (add (i+1,j) vis) mat cond | move_left (i,j) mat cond && not (visited (i,j-1) vis) = visit (i,j-1) (add (i,j-1) vis) mat cond | move_up (i,j) mat cond && not (visited (i-1,j) vis) = visit (i-1,j) (add (i-1,j) vis) mat cond | otherwise = vis

    Read the article

  • Flip rotation matrix

    - by azer89
    right now i'm doing character control with kinect. Basically i need to mirror the joint orientation because the character faces the player. Somehow by googling through internet i've done it and everything works very well. But i have little idea about how the math works, here's my code: //------------------------------------------------------------------------------------- Ogre::Quaternion JointOrientationCalculator::buildQuaternion(Ogre::Vector3 xAxis, Ogre::Vector3 yAxis, Ogre::Vector3 zAxis) { Ogre::Matrix3 mat; if(isMirror) { mat = Ogre::Matrix3(xAxis.x, yAxis.x, zAxis.x, xAxis.y, yAxis.y, zAxis.y, xAxis.z, yAxis.z, zAxis.z); Ogre::Matrix3 flipMat(1, 0, 0, 0, 1, 0, 0, 0, -1); mat = flipMat * mat * flipMat; } else { mat = Ogre::Matrix3(xAxis.x, -yAxis.x, zAxis.x, -xAxis.y, yAxis.y, -zAxis.y, xAxis.z, -yAxis.z, zAxis.z); } Ogre::Quaternion q; q.FromRotationMatrix(mat); return q; } when i need to mirror/flip it by axes z i calculate mat = flipMat * mat * flipMat; but i don't understand how this equation works.

    Read the article

  • compiling opencv 2.4 on a 64 bit mac in Xcode

    - by Walt
    I have an opencv project that I've been developing under ubuntu 12.04, on a parellels VM on a mac which has an x86_64 architecture. There have been many screen switching performance issues that I believe are due to the VM, where linux video modes flip around for a couple seconds while camera access is made by the opencv application. I decided to moved the project into Xcode on the mac side of the computer to continue the opencv development. However, I'm not that familiar with xcode and am having trouble getting the project to build correctly there. I have xcode installed. I downloaded and decompressed the latest version of opencv on the mac, and ran: ~/src/opencv/build/cmake-gui -G Xcode .. per the instructions from willowgarage and various other locations. This appeared to work fine (however I'm wondering now if I'm missing an architecture setting in here, although it is 64-bit intel in Xcode). I then setup an xcode project with the source files from the linux project and changed the include directories to use /opt/local/include/... rather than the /usr/local/include/... I switched xcode to use the LLVM GCC compiler in the build settings for the project then set the Apple LLVM Dialog for C++ to Language Dialect to GNU++11 (which seems possibly inconsistant with the line above) I'm not using a makefile in xcode, (that I'm aware of - it has its own project file...) I was also running into a linker issue that looked like they may be resolved with the addition of this linker flag: -lopencv_video based on a similar posting here: other thread however in that case the person was using a Makefile in their project. I've tried adding this linker flag under "Other Linker Flags" in xcode build settings but still get build errors. I think I may have two issues here, one with the architecture settings when building the opencv libraries with Cmake, and one with the linker flag settings in my project. Currently the build error list looks like this: Undefined symbols for architecture x86_64: "cv::_InputArray::_InputArray(cv::Mat const&)", referenced from: _main in main.o "cv::_OutputArray::_OutputArray(cv::Mat&)", referenced from: _main in main.o "cv::Mat::deallocate()", referenced from: cv::Mat::release() in main.o "cv::Mat::copySize(cv::Mat const&)", referenced from: cv::Mat::Mat(cv::Mat const&)in main.o cv::Mat::operator=(cv::Mat const&)in main.o "cv::Mat::Mat(_IplImage const*, bool)", referenced from: _main in main.o "cv::imread(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)", referenced from: _main in main.o ---SNIP--- ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status Can anyone provide some guidance on what to try next? Thanks, Walt

    Read the article

  • Updating physics for animated models

    - by Mathias Hölzl
    For a new game we have do set up a scene with a minimum of 30 bone animated models.(shooter) The problem is that the update process for the animated models takes too long. Thats what I do: Each character has ~30 bones and for every update tick the animation gets calculated and every bone fires a event with the new matrix. The physics receives the event with the new matrix and updates the collision shape for that bone. The time that it takes to build the animation isn't that bad (0.2ms for 30 Bones - 6ms for 30 models). But the main problem is that the physic engine (Bullet) uses a diffrent matrix for transformation and so its necessary to convert it. Code for matrix conversion: (~0.005ms) btTransform CLEAR_PHYSICS_API Mat_to_btTransform( Mat mat ) { btMatrix3x3 bulletRotation; btVector3 bulletPosition; XMFLOAT4X4 matData = mat.GetStorage(); // copy rotation matrix for ( int row=0; row<3; ++row ) for ( int column=0; column<3; ++column ) bulletRotation[row][column] = matData.m[column][row]; for ( int column=0; column<3; ++column ) bulletPosition[column] = matData.m[3][column]; return btTransform( bulletRotation, bulletPosition ); } The function for updating the transform(Physic): void CLEAR_PHYSICS_API BulletPhysics::VKinematicMove(Mat mat, ActorId aid) { if ( btRigidBody * const body = FindActorBody( aid ) ) { btTransform tmp = Mat_to_btTransform( mat ); body->setWorldTransform( tmp ); } } The real problem is the function FindActorBody(id): ActorIDToBulletActorMap::const_iterator found = m_actorBodies.find( id ); if ( found != m_actorBodies.end() ) return found->second; All physic actors are stored in m_actorBodies and thats why the updating process takes to long. But I have no idea how I could avoid this. Friendly greedings, Mathias

    Read the article

  • Java code optimization on matrix windowing computes in more time

    - by rano
    I have a matrix which represents an image and I need to cycle over each pixel and for each one of those I have to compute the sum of all its neighbors, ie the pixels that belong to a window of radius rad centered on the pixel. I came up with three alternatives: The simplest way, the one that recomputes the window for each pixel The more optimized way that uses a queue to store the sums of the window columns and cycling through the columns of the matrix updates this queue by adding a new element and removing the oldes The even more optimized way that does not need to recompute the queue for each row but incrementally adjusts a previously saved one I implemented them in c++ using a queue for the second method and a combination of deques for the third (I need to iterate through their elements without destructing them) and scored their times to see if there was an actual improvement. it appears that the third method is indeed faster. Then I tried to port the code to Java (and I must admit that I'm not very comfortable with it). I used ArrayDeque for the second method and LinkedLists for the third resulting in the third being inefficient in time. Here is the simplest method in C++ (I'm not posting the java version since it is almost identical): void normalWindowing(int mat[][MAX], int cols, int rows, int rad){ int i, j; int h = 0; for (i = 0; i < rows; ++i) { for (j = 0; j < cols; j++) { h = 0; for (int ry =- rad; ry <= rad; ry++) { int y = i + ry; if (y >= 0 && y < rows) { for (int rx =- rad; rx <= rad; rx++) { int x = j + rx; if (x >= 0 && x < cols) { h += mat[y][x]; } } } } } } } Here is the second method (the one optimized through columns) in C++: void opt1Windowing(int mat[][MAX], int cols, int rows, int rad){ int i, j, h, y, col; queue<int>* q = NULL; for (i = 0; i < rows; ++i) { if (q != NULL) delete(q); q = new queue<int>(); h = 0; for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][rx]; } } q->push(mem); h += mem; } } for (j = 1; j < cols; j++) { col = j + rad; if (j - rad > 0) { h -= q->front(); q->pop(); } if (j + rad < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][col]; } } q->push(mem); h += mem; } } } } And here is the Java version: public static void opt1Windowing(int [][] mat, int rad){ int i, j = 0, h, y, col; int cols = mat[0].length; int rows = mat.length; ArrayDeque<Integer> q = null; for (i = 0; i < rows; ++i) { q = new ArrayDeque<Integer>(); h = 0; for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][rx]; } } q.addLast(mem); h += mem; } } j = 0; for (j = 1; j < cols; j++) { col = j + rad; if (j - rad > 0) { h -= q.peekFirst(); q.pop(); } if (j + rad < cols) { int mem = 0; for (int ry =- rad; ry <= rad; ry++) { y = i + ry; if (y >= 0 && y < rows) { mem += mat[y][col]; } } q.addLast(mem); h += mem; } } } } I recognize this post will be a wall of text. Here is the third method in C++: void opt2Windowing(int mat[][MAX], int cols, int rows, int rad){ int i = 0; int j = 0; int h = 0; int hh = 0; deque< deque<int> *> * M = new deque< deque<int> *>(); for (int ry = 0; ry <= rad; ry++) { if (ry < rows) { deque<int> * q = new deque<int>(); M->push_back(q); for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int val = mat[ry][rx]; q->push_back(val); h += val; } } } } deque<int> * C = new deque<int>(M->front()->size()); deque<int> * Q = new deque<int>(M->front()->size()); deque<int> * R = new deque<int>(M->size()); deque< deque<int> *>::iterator mit; deque< deque<int> *>::iterator mstart = M->begin(); deque< deque<int> *>::iterator mend = M->end(); deque<int>::iterator rit; deque<int>::iterator rstart = R->begin(); deque<int>::iterator rend = R->end(); deque<int>::iterator cit; deque<int>::iterator cstart = C->begin(); deque<int>::iterator cend = C->end(); for (mit = mstart, rit = rstart; mit != mend, rit != rend; ++mit, ++rit) { deque<int>::iterator pit; deque<int>::iterator pstart = (* mit)->begin(); deque<int>::iterator pend = (* mit)->end(); for(cit = cstart, pit = pstart; cit != cend && pit != pend; ++cit, ++pit) { (* cit) += (* pit); (* rit) += (* pit); } } for (i = 0; i < rows; ++i) { j = 0; if (i - rad > 0) { deque<int>::iterator cit; deque<int>::iterator cstart = C->begin(); deque<int>::iterator cend = C->end(); deque<int>::iterator pit; deque<int>::iterator pstart = (M->front())->begin(); deque<int>::iterator pend = (M->front())->end(); for(cit = cstart, pit = pstart; cit != cend; ++cit, ++pit) { (* cit) -= (* pit); } deque<int> * k = M->front(); M->pop_front(); delete k; h -= R->front(); R->pop_front(); } int row = i + rad; if (row < rows && i > 0) { deque<int> * newQ = new deque<int>(); M->push_back(newQ); deque<int>::iterator cit; deque<int>::iterator cstart = C->begin(); deque<int>::iterator cend = C->end(); int rx; int tot = 0; for (rx = 0, cit = cstart; rx <= rad; rx++, ++cit) { if (rx < cols) { int val = mat[row][rx]; newQ->push_back(val); (* cit) += val; tot += val; } } R->push_back(tot); h += tot; } hh = h; copy(C->begin(), C->end(), Q->begin()); for (j = 1; j < cols; j++) { int col = j + rad; if (j - rad > 0) { hh -= Q->front(); Q->pop_front(); } if (j + rad < cols) { int val = 0; for (int ry =- rad; ry <= rad; ry++) { int y = i + ry; if (y >= 0 && y < rows) { val += mat[y][col]; } } hh += val; Q->push_back(val); } } } } And finally its Java version: public static void opt2Windowing(int [][] mat, int rad){ int cols = mat[0].length; int rows = mat.length; int i = 0; int j = 0; int h = 0; int hh = 0; LinkedList<LinkedList<Integer>> M = new LinkedList<LinkedList<Integer>>(); for (int ry = 0; ry <= rad; ry++) { if (ry < rows) { LinkedList<Integer> q = new LinkedList<Integer>(); M.addLast(q); for (int rx = 0; rx <= rad; rx++) { if (rx < cols) { int val = mat[ry][rx]; q.addLast(val); h += val; } } } } int firstSize = M.getFirst().size(); int mSize = M.size(); LinkedList<Integer> C = new LinkedList<Integer>(); LinkedList<Integer> Q = null; LinkedList<Integer> R = new LinkedList<Integer>(); for (int k = 0; k < firstSize; k++) { C.add(0); } for (int k = 0; k < mSize; k++) { R.add(0); } ListIterator<LinkedList<Integer>> mit; ListIterator<Integer> rit; ListIterator<Integer> cit; ListIterator<Integer> pit; for (mit = M.listIterator(), rit = R.listIterator(); mit.hasNext();) { Integer r = rit.next(); int rsum = 0; for (cit = C.listIterator(), pit = (mit.next()).listIterator(); cit.hasNext();) { Integer c = cit.next(); Integer p = pit.next(); rsum += p; cit.set(c + p); } rit.set(r + rsum); } for (i = 0; i < rows; ++i) { j = 0; if (i - rad > 0) { for(cit = C.listIterator(), pit = M.getFirst().listIterator(); cit.hasNext();) { Integer c = cit.next(); Integer p = pit.next(); cit.set(c - p); } M.removeFirst(); h -= R.getFirst(); R.removeFirst(); } int row = i + rad; if (row < rows && i > 0) { LinkedList<Integer> newQ = new LinkedList<Integer>(); M.addLast(newQ); int rx; int tot = 0; for (rx = 0, cit = C.listIterator(); rx <= rad; rx++) { if (rx < cols) { Integer c = cit.next(); int val = mat[row][rx]; newQ.addLast(val); cit.set(c + val); tot += val; } } R.addLast(tot); h += tot; } hh = h; Q = new LinkedList<Integer>(); Q.addAll(C); for (j = 1; j < cols; j++) { int col = j + rad; if (j - rad > 0) { hh -= Q.getFirst(); Q.pop(); } if (j + rad < cols) { int val = 0; for (int ry =- rad; ry <= rad; ry++) { int y = i + ry; if (y >= 0 && y < rows) { val += mat[y][col]; } } hh += val; Q.addLast(val); } } } } I guess that most is due to the poor choice of the LinkedList in Java and to the lack of an efficient (not shallow) copy method between two LinkedList. How can I improve the third Java method? Am I doing some conceptual error? As always, any criticisms is welcome. UPDATE Even if it does not solve the issue, using ArrayLists, as being suggested, instead of LinkedList improves the third method. The second one performs still better (but when the number of rows and columns of the matrix is lower than 300 and the window radius is small the first unoptimized method is the fastest in Java)

    Read the article

  • Loops on a Matlab program

    - by lebland-matlab
    I have 3 sets of 10 vectors each, and I want to take 2 vectors from the first set , 2 vectors from the second set and 3 vectors from the third set . My goal is to make a loop to implement the following program, knowing that after each calculation, the result shall be saved in a new file. My problem is that I can not handle the indices included in the strings. I try to use multiple loops to scan the 3 sets in the order of indices. loops should contain the following program clc; clear all; load('C:\Users\Documents\MATLAB\myFile\matrice_F.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_G.mat'); F = m_F; G = m_G; load('C:\Users\Documents\MATLAB\myFile\matrice_J.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_K.mat'); J = m_J; K = m_K; load('C:\Users\Documents\MATLAB\myFile\matrice_N.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_O.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_P.mat'); N = m_N ; O = m_O; P = m_P; [A,B,C,D,E] = myFun(F,G,J,K,N,O,P); file_name = 'matrice_final.mat'; save(file_name,'A','B','C','D','E');

    Read the article

  • How can I make this Matlab program possible?

    - by lebland-matlab
    I do not know how to combine the indices with the characters, Could you help me to make this program possible: clc; clear all; set1={F,G,FF,GG,X,Y,XX,L,BH,JK}; %set of name vectors set2={J,K,HG,UY,TR,BC,XW,IOP,ES,QA}; %set of name vectors set3={AJ,RK,DS,TU,WS,ZZE,ZXW,TYP,ZAA,QWW}; %set of name vectors for i=1:1:9 load('C:\Users\Documents\MATLAB\myFile\matrice_'set1(i)'.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_'set1(i+1)'.mat'); 'set1(i)' = m_'set1(i)'; 'set1(i+1)' = m_'set1(i+1)'; for j=1:1:9 load('C:\Users\Documents\MATLAB\myFile\matrice_'set2(j)'.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_'set2(j+1)'.mat'); 'set2(j)' = m_'set2(j)'; 'set2(j+1)' = m_'set2(j+1)'; for k=1:1:8 load('C:\Users\Documents\MATLAB\myFile\matrice_'set3(k)'.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_'set3(k+1)'.mat'); load('C:\Users\Documents\MATLAB\myFile\matrice_'set3(k+2)'.mat'); 'set3(k)' = m_'set3(k)' ; 'set3(k+1)' = m_'set3(k+1)'; 'set3(k+2)' = m_'set3(k+2)'; [Result1'index',Result2'index',Result3'index',Result4'index',Result5'index'] = myFun('set1(i)','set1(i+1)','set2(j)','set2(j+1)','set3(k)','set3(k+1)','set3(k+2)'); %% 9x9x8=648 index=1,2,...,648 file_name = 'matrice_final'index'.mat'; save(file_name,'Result1'index'','Result2'index'','Result3'index'','Result4'index'','Result5'index''); clear 'set3(k)' 'set3(k+1)' 'set3(k+2)' end clear 'set2(j)' 'set2(j+1)' end clear 'set1(i)' 'set1(i+1)' end

    Read the article

  • asp.net mvc insert doesnt seem to work for me....

    - by Pandiya Chendur
    My controller's call to repository insert method all the values are passed but it doesn't get inserted in my table.. My controller method, [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Exclude = "Id")]FormCollection collection) { try { MaterialsObj materialsObj = new MaterialsObj(); materialsObj.Mat_Name = collection["Mat_Name"]; materialsObj.Mes_Id = Convert.ToInt64(collection["MeasurementType"]); materialsObj.Mes_Name = collection["Mat_Type"]; materialsObj.CreatedDate = System.DateTime.Now; materialsObj.CreatedBy = Convert.ToInt64(1); materialsObj.IsDeleted = Convert.ToInt64(1); consRepository.createMaterials(materialsObj); return RedirectToAction("Index"); } catch { return View(); } } and my repository, public MaterialsObj createMaterials(MaterialsObj materialsObj) { Material mat = new Material(); mat.Mat_Name = materialsObj.Mat_Name; mat.Mat_Type = materialsObj.Mes_Name; mat.MeasurementTypeId = materialsObj.Mes_Id; mat.Created_Date = materialsObj.CreatedDate; mat.Created_By = materialsObj.CreatedBy; mat.Is_Deleted = materialsObj.IsDeleted; db.Materials.InsertOnSubmit(mat); return materialsObj; } What am i missing here any suggestion....

    Read the article

  • How to change by using CVGrayscaleMat

    - by Babul
    With the following code the image showed as above is converted as below image... Their it's showing black background with gray lines.....i want white background with gray lines .. Please guide me .. i am new to iPhone Thanks alot in Advance - (void)viewDidLoad { [super viewDidLoad]; // Initialise video capture - only supported on iOS device NOT simulator #if TARGET_IPHONE_SIMULATOR NSLog(@"Video capture is not supported in the simulator"); #else _videoCapture = new cv::VideoCapture; if (!_videoCapture->open(CV_CAP_AVFOUNDATION)) { NSLog(@"Failed to open video camera"); } #endif // Load a test image and demonstrate conversion between UIImage and cv::Mat UIImage *testImage = [UIImage imageNamed:@"testimage.jpg"]; double t; int times = 10; //-------------------------------- // Convert from UIImage to cv::Mat NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; t = (double)cv::getTickCount(); for (int i = 0; i < times; i++) { cv::Mat tempMat = [testImage CVMat]; } t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency() / times; [pool release]; NSLog(@"UIImage to cv::Mat: %gms", t); //------------------------------------------ // Convert from UIImage to grayscale cv::Mat pool = [[NSAutoreleasePool alloc] init]; t = (double)cv::getTickCount(); for (int i = 0; i < times; i++) { cv::Mat tempMat = [testImage CVGrayscaleMat]; } t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency() / times; [pool release]; NSLog(@"UIImage to grayscale cv::Mat: %gms", t); //-------------------------------- // Convert from cv::Mat to UIImage cv::Mat testMat = [testImage CVMat]; t = (double)cv::getTickCount(); for (int i = 0; i < times; i++) { UIImage *tempImage = [[UIImage alloc] initWithCVMat:testMat]; [tempImage release]; } t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency() / times; NSLog(@"cv::Mat to UIImage: %gms", t); // Process test image and force update of UI _lastFrame = testMat; [self sliderChanged:nil]; } - (IBAction)capture:(id)sender { if (_videoCapture && _videoCapture->grab()) { (*_videoCapture) >> _lastFrame; [self processFrame]; } else { NSLog(@"Failed to grab frame"); } } - (void)processFrame { double t = (double)cv::getTickCount(); cv::Mat grayFrame, output; // Convert captured frame to grayscale cv::cvtColor(_lastFrame, grayFrame, cv::COLOR_RGB2GRAY); // Perform Canny edge detection using slide values for thresholds cv::Canny(grayFrame, output, _lowSlider.value * kCannyAperture * kCannyAperture, _highSlider.value * kCannyAperture * kCannyAperture, kCannyAperture); t = 1000 * ((double)cv::getTickCount() - t) / cv::getTickFrequency(); // Display result self.imageView.image = [UIImage imageWithCVMat:output]; self.elapsedTimeLabel.text = [NSString stringWithFormat:@"%.1fms", t]; }

    Read the article

  • Python bindings for C++ code using OpenCV giving segmentation fault

    - by lightalchemist
    I'm trying to write a python wrapper for some C++ code that make use of OpenCV but I'm having difficulties returning the result, which is a OpenCV C++ Mat object, to the python interpreter. I've looked at OpenCV's source and found the file cv2.cpp which has conversions functions to perform conversions to and fro between PyObject* and OpenCV's Mat. I made use of those conversions functions but got a segmentation fault when I tried to use them. I basically need some suggestions/sample code/online references on how to interface python and C++ code that make use of OpenCV, specifically with the ability to return OpenCV's C++ Mat to the python interpreter or perhaps suggestions on how/where to start investigating the cause of the segmentation fault. Currently I'm using Boost Python to wrap the code. Thanks in advance to any replies. The relevant code: // This is the function that is giving the segmentation fault. PyObject* ABC::doSomething(PyObject* image) { Mat m; pyopencv_to(image, m); // This line gives segmentation fault. // Some code to create cppObj from CPP library that uses OpenCV cv::Mat processedImage = cppObj->align(m); return pyopencv_from(processedImage); } The conversion functions taken from OpenCV's source follows. The conversion code gives segmentation fault at the commented line with "if (!PyArray_Check(o)) ...". static int pyopencv_to(const PyObject* o, Mat& m, const char* name = "<unknown>", bool allowND=true) { if(!o || o == Py_None) { if( !m.data ) m.allocator = &g_numpyAllocator; return true; } if( !PyArray_Check(o) ) // Segmentation fault inside PyArray_Check(o) { failmsg("%s is not a numpy array", name); return false; } int typenum = PyArray_TYPE(o); int type = typenum == NPY_UBYTE ? CV_8U : typenum == NPY_BYTE ? CV_8S : typenum == NPY_USHORT ? CV_16U : typenum == NPY_SHORT ? CV_16S : typenum == NPY_INT || typenum == NPY_LONG ? CV_32S : typenum == NPY_FLOAT ? CV_32F : typenum == NPY_DOUBLE ? CV_64F : -1; if( type < 0 ) { failmsg("%s data type = %d is not supported", name, typenum); return false; } int ndims = PyArray_NDIM(o); if(ndims >= CV_MAX_DIM) { failmsg("%s dimensionality (=%d) is too high", name, ndims); return false; } int size[CV_MAX_DIM+1]; size_t step[CV_MAX_DIM+1], elemsize = CV_ELEM_SIZE1(type); const npy_intp* _sizes = PyArray_DIMS(o); const npy_intp* _strides = PyArray_STRIDES(o); bool transposed = false; for(int i = 0; i < ndims; i++) { size[i] = (int)_sizes[i]; step[i] = (size_t)_strides[i]; } if( ndims == 0 || step[ndims-1] > elemsize ) { size[ndims] = 1; step[ndims] = elemsize; ndims++; } if( ndims >= 2 && step[0] < step[1] ) { std::swap(size[0], size[1]); std::swap(step[0], step[1]); transposed = true; } if( ndims == 3 && size[2] <= CV_CN_MAX && step[1] == elemsize*size[2] ) { ndims--; type |= CV_MAKETYPE(0, size[2]); } if( ndims > 2 && !allowND ) { failmsg("%s has more than 2 dimensions", name); return false; } m = Mat(ndims, size, type, PyArray_DATA(o), step); if( m.data ) { m.refcount = refcountFromPyObject(o); m.addref(); // protect the original numpy array from deallocation // (since Mat destructor will decrement the reference counter) }; m.allocator = &g_numpyAllocator; if( transposed ) { Mat tmp; tmp.allocator = &g_numpyAllocator; transpose(m, tmp); m = tmp; } return true; } static PyObject* pyopencv_from(const Mat& m) { if( !m.data ) Py_RETURN_NONE; Mat temp, *p = (Mat*)&m; if(!p->refcount || p->allocator != &g_numpyAllocator) { temp.allocator = &g_numpyAllocator; m.copyTo(temp); p = &temp; } p->addref(); return pyObjectFromRefcount(p->refcount); } My python test program: import pysomemodule # My python wrapped library. import cv2 def main(): myobj = pysomemodule.ABC("faces.train") # Create python object. This works. image = cv2.imread('61.jpg') processedImage = myobj.doSomething(image) cv2.imshow("test", processedImage) cv2.waitKey() if __name__ == "__main__": main()

    Read the article

  • Manipulating matrix operations (transpose, negation, addition, and mutiplication) using functions in

    - by user292489
    I was trying to manipulate matrices in my input file using functions. My input file is: A 3 3 1 2 3 4 5 6 7 8 9 B 3 3 1 0 0 0 1 0 0 0 1 C 2 3 3 5 8 -1 -2 -3 D 3 5 0 0 0 1 0 1 0 1 0 1 0 1 0 0 1 E 1 1 10 F 3 10 1 0 2 0 3 0 4 0 5 0 0 2 3 -1 -3 -4 -3 8 3 7 0 0 0 4 6 5 8 2 -1 10 I am having trouble in implementing the functions that I declared. I assumed my program will perform those operations: transpose, negate, add, and multiply matices according to the users choice: /* once this program is compiled and executed, it will perform the basic matrix * operations: negation, transpose, addition, and multiplication. */ #include <stdio.h> #include <stdlib.h> #define MAX 10 int readmatrix(FILE *input, char martixname[6],int , mat[10][10], int i, int j); void printmatrix(char matrixname[6], int mat[10][10], int i, int j); void Negate(char matrixname[6], int mat[10][10], int i, int j); void add(char matrixname[6], int mat[10][10],int i, int k); void multiply(char matrixname[], int mat[][10], char A[], int i, int k); void transpose (char matrixname[], int mat[][10], char A[], int); void printT(int mat[][10], int); int selctoption(); char selectmatrix(); int main(int argc, char *argv[]) { char matrixtype[6]; int mat[][10]; FILE *filein; int size; int optionop; int matrixop; int option; if (argc != 2) { printf("Usage: executable input.\n"); exit(0); } filein = fopen(argv[1], "r"); if (!filein) { printf("ERROR: input file not found.\n"); exit (0); } size = readmatrix (filein, matrixtype); printmatrix(matrix[][10], size); option = selectoption(); matrixtype = selectmatrix(); //printf("You have: %5.2f ", deposit); optionop = readmatrix(option, matrix[][10], size); if (choiceop == 6) { printf("Thanks for using the matrix operation program.\n"); exit(0); } printf("Please select from the following matrix operations:\n") printf("\t1. Print matrix\n"); printf("\t2. Negate matrix\n"); printf("\t3. Transpose matrix\n"); printf("\t4. Add matrices\n"); printf("\t5. Multiply matrices\n"); printf("\t6. Quit\n"); fclose(filein); return 0; } do { printf("Please select option(1-%d):", optionop); scanf("%d", &matrixop); } while(matrixop <= 0 || matrixop > optionop); void readmatrix (FILE *in, int mat[][10], char A[], int i, int j) { int i=0,j = 0; while (fscanf(in, "%d", &mat[i][j]) != EOF) return 0; } // I would appreciate anyone's feedback.

    Read the article

  • manuplating matrix operation(transpose, negation, addition, and mutipication) using functions in c

    - by user292489
    i was trying to manuplate matrices in my input file using functions. my input file is, A 3 3 1 2 3 4 5 6 7 8 9 B 3 3 1 0 0 0 1 0 0 0 1 C 2 3 3 5 8 -1 -2 -3 D 3 5 0 0 0 1 0 1 0 1 0 1 0 1 0 0 1 E 1 1 10 F 3 10 1 0 2 0 3 0 4 0 5 0 0 2 3 -1 -3 -4 -3 8 3 7 0 0 0 4 6 5 8 2 -1 10 i am having trouble in impementing the funcitons that i declared. i assumed my program will perform those operations: transpose, negate, add, and mutiply matices according to the users choise: /* once this program is compliled and excuted, it will perform the basic matrix operations: negation, transpose,a\ ddition, and multiplication. */ #include <stdio.h> #include <stdlib.h> #define MAX 10 int readmatrix(FILE *input, char martixname[6],int , mat[10][10], int i, int j); void printmatrix(char matrixname[6], int mat[10][10], int i, int j); void Negate(char matrixname[6], int mat[10][10], int i, int j); void add(char matrixname[6], int mat[10][10],int i, int k); void multiply(char matrixname[], int mat[][10], char A[], int i, int k); void transpose (char matrixname[], int mat[][10], char A[], int); void printT(int mat[][10], int); int selctoption(); char selectmatrix(); int main(int argc, char *argv[]) { char matrixtype[6]; int mat[][10]; FILE *filein; int size; int optionop; int matrixop; int option; if (argc != 2) { printf("Usage: excutable input.\n"); exit (0); } filein = fopen(argv[1], "r"); if (!filein) { printf("ERROR: input file not found.\n"); exit (0); } size = readmatrix (filein, matrixtype); printmatrix(matrix[][10], size); option = selectoption(); matrixtype = selectmatrix(); //printf("You have: %5.2f ", deposit); optionop = readmatrix(option, matrix[][10], size); if (choiceop == 6) { printf("Thanks for using the matrix operation program.\n"); exit(0); } printf("Please select from the following matrix operations:\n") printf("\t1. Print matrix\n"); printf("\t2. Negate matrix\n"); printf("\t3. Transpose matrix\n"); printf("\t4. Add matrices\n"); printf("\t5. Multiply matrices\n"); printf("\t6. Quit\n"); fclose(filein); return 0; } do { printf("Please select option(1-%d):", optionop); scanf("%d", &matrixop); }while(matrixop <= 0 || matrixop > optionop); void readmatrix (FILE *in, int mat[][10], char A[], int i, int j) { int i=0,j = 0; while (fscanf(in, "%d", &mat[i][j]) != EOF) return 0; } // i would apprtaite anyones feedback. //thank you!

    Read the article

  • Generic function that accept a table and column name and returns all the primary key values that mat

    - by nashr rafeeg
    i have functions that look like this that is littered through out the code def get_M_status(S): M_id = merital.select(merital.c.marital_status_description == S).execute().fetchone() if M_id == None: print "Warning: No Marital id found for %s Merital status to Single" % S M_id = merital.select(merital.c.marital_status_description == "Single").execute().fetchone() return M_id[0] i was wondering if their is a way to write a generic function where i can pass the relevant values ie: table name primary key column filter column and filter value cheers

    Read the article

  • How do I create an empty array/matrix in NumPy?

    - by Ben
    I'm sure I must be being very dumb, but I can't figure out how to use an array or matrix in the way that I would normally use a list. I.e., I want to create an empty array (or matrix) and then add one column (or row) to it at a time. At the moment the only way I can find to do this is like: mat = None for col in columns: if mat is None: mat = col else: mat = hstack((mat, col)) Whereas if it were a list, I'd do something like this: list = [] for item in data: list.append(item) Is there a way to use that kind of notation for NumPy arrays or matrices? (Or a better way -- I'm still pretty new to python!)

    Read the article

1 2 3 4 5 6 7 8 9 10  | Next Page >