template<typename _Tp> void resizeMatChannelType(Mat& src_mat, Mat& dest_mat, double val) { CV_Assert(!src_mat.empty() && !dest_mat.empty()); CV_Assert(src_mat.cols == dest_mat.cols && src_mat.rows == dest_mat.rows); int src_channel = src_mat.channels(); int dest_channel = dest_mat.channels(); int diff_channel = dest_channel - src_channel; int byte_size = src_mat.elemSize1(); int src_block = src_mat.elemSize(); int dest_block = dest_mat.elemSize(); int mat_size = src_mat.rows * src_mat.cols; int copy_channel = (diff_channel < 0) ? dest_channel : src_channel; int copy_byte = copy_channel * byte_size; int type = src_mat.depth(); unsigned char* src_data = src_mat.data; unsigned char* dest_data = dest_mat.data; unsigned char* dest_ptr; int i,j; for(i=0; i<mat_size; i++){ memcpy(dest_data+i*dest_block, src_data+i*src_block, copy_byte); for(j=0;j<diff_channel;j++){ dest_ptr = dest_data + i*dest_block + copy_byte + j*byte_size; *((_Tp*)dest_ptr) = (_Tp)val; } } }
static void DCT_1D( const Mat& _src, Mat& _dst, int flags, const Mat& _wave=Mat() ) { _dst.create( _src.size(), _src.type() ); int i, j, n = _dst.cols + _dst.rows - 1; Mat wave = _wave; int srcstep = 1, dststep = 1; double* w; CV_Assert( _src.cols + _src.rows - 1 == n); if( wave.empty() ) wave = initDCTWave( n, (flags & DFT_INVERSE) != 0 ); w = wave.ptr<double>(); if( !_src.isContinuous() ) srcstep = (int)(_src.step/_src.elemSize()); if( !_dst.isContinuous() ) dststep = (int)(_dst.step/_dst.elemSize()); if( _src.type() == CV_32FC1 ) { float *dst = _dst.ptr<float>(); for( i = 0; i < n; i++, dst += dststep ) { const float* src = _src.ptr<float>(); double sum = 0; for( j = 0; j < n; j++, src += srcstep ) sum += src[0]*w[j]; w += n; dst[0] = (float)sum; } } else if( _src.type() == CV_64FC1 ) { double *dst = _dst.ptr<double>(); for( i = 0; i < n; i++, dst += dststep ) { const double* src = _src.ptr<double>(); double sum = 0; for( j = 0; j < n; j++, src += srcstep ) sum += src[0]*w[j]; w += n; dst[0] = sum; } } else assert(0); }
string test_plateRecognizeMain() { const char* fileName = "resources/image/7.jpg"; Mat img = cv::imread(fileName); if (img.empty()) { cout << "plate is empty" << endl; return ""; } int size = img.elemSize()*img.total(); vector<uchar> buff;//buffer for coding vector<int> param = vector<int>(2); param[0] = CV_IMWRITE_JPEG_QUALITY; param[1] = 95;//default(95) 0-100 imencode(".jpg", img, buff, param); uchar *pImg = &(buff[0]); char *ppImg = (char*)pImg; //Mat src = imdecode(Mat(1, size, CV_8U, pp), IMREAD_COLOR); caffepr::CaffeRecognise cr; string res; res = cr.process(ppImg,size ); cout << "检测的车牌号为:" <<endl<< res << endl; return res; }
float FAST::CFastImage::FastSum( Mat& _img, int _pVec[], int _n ) { size_t elemSize = _img.elemSize(); float sum = 0.0f; FOR (i, _n) sum += (float)(*(uchar*)(_img.data+_pVec[i]*elemSize)); return sum; }
//http://stackoverflow.com/questions/16809833/opencv-image-loading-for-opengl-texture void loadCVimageAsTexture(Mat img) { if(img.empty()){ cout << "Image is empty" << endl; } else{ //align the opencv image to opengl 4-byte alignment glPixelStorei(GL_UNPACK_ALIGNMENT, (img.step & 3) ? 1:4); //set length of one complete row glPixelStorei(GL_UNPACK_ROW_LENGTH, img.step/img.elemSize()); //OpenCv and Opengl stores images differently, flip the image so it is correct cv::flip(img, img, 0); GLuint tex_2d; glGenTextures(1, &tex_2d); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex_2d); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.cols, img.rows, 0, GL_BGR, GL_UNSIGNED_BYTE, img.ptr()); } }
void repeat(InputArray _src, int ny, int nx, OutputArray _dst) { CV_Assert( _src.dims() <= 2 ); CV_Assert( ny > 0 && nx > 0 ); Size ssize = _src.size(); _dst.create(ssize.height*ny, ssize.width*nx, _src.type()); CV_OCL_RUN(_dst.isUMat(), ocl_repeat(_src, ny, nx, _dst)) Mat src = _src.getMat(), dst = _dst.getMat(); Size dsize = dst.size(); int esz = (int)src.elemSize(); int x, y; ssize.width *= esz; dsize.width *= esz; for( y = 0; y < ssize.height; y++ ) { for( x = 0; x < dsize.width; x += ssize.width ) memcpy( dst.data + y*dst.step + x, src.data + y*src.step, ssize.width ); } for( ; y < dsize.height; y++ ) memcpy( dst.data + y*dst.step, dst.data + (y - ssize.height)*dst.step, dsize.width ); }
static ImageDecoder findDecoder( const Mat& buf ) { size_t i, maxlen = 0; if( buf.rows*buf.cols < 1 || !buf.isContinuous() ) return ImageDecoder(); for( i = 0; i < codecs.decoders.size(); i++ ) { size_t len = codecs.decoders[i]->signatureLength(); maxlen = std::max(maxlen, len); } string signature(maxlen, ' '); size_t bufSize = buf.rows*buf.cols*buf.elemSize(); maxlen = std::min(maxlen, bufSize); memcpy( &signature[0], buf.data, maxlen ); for( i = 0; i < codecs.decoders.size(); i++ ) { if( codecs.decoders[i]->checkSignature(signature) ) return codecs.decoders[i]->newDecoder(); } return ImageDecoder(); }
cv::GlBuffer::Impl::Impl(const Mat& m, unsigned int target) : buffer_(0) { if (!glFuncTab()->isGlContextInitialized()) throw_nogl; CV_DbgAssert(m.rows > 0 && m.cols > 0); CV_DbgAssert(m.depth() >= 0 && m.depth() <= CV_64F); CV_Assert(m.isContinuous()); glFuncTab()->genBuffers(1, &buffer_); CV_CheckGlError(); CV_Assert(buffer_ != 0); size_t size = m.rows * m.cols * m.elemSize(); glFuncTab()->bindBuffer(target, buffer_); CV_CheckGlError(); glFuncTab()->bufferData(target, size, m.data, GL_DYNAMIC_DRAW); CV_CheckGlError(); glFuncTab()->bindBuffer(target, 0); #ifdef HAVE_CUDA if (g_isCudaGlDeviceInitialized) cudaGlInterop_.registerBuffer(buffer_); #endif }
bool WebPDecoder::readData(Mat &img) { if( m_width > 0 && m_height > 0 ) { if (img.cols != m_width || img.rows != m_height || img.type() != m_type) { img.create(m_height, m_width, m_type); } uchar* out_data = img.data; size_t out_data_size = img.cols * img.rows * img.elemSize(); uchar *res_ptr = 0; if (channels == 3) { res_ptr = WebPDecodeBGRInto(data.data, data.total(), out_data, out_data_size, img.step); } else if (channels == 4) { res_ptr = WebPDecodeBGRAInto(data.data, data.total(), out_data, out_data_size, img.step); } if(res_ptr == out_data) { return true; } } return false; }
cv::ogl::Buffer::Buffer(InputArray arr, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) { #ifndef HAVE_OPENGL (void) arr; (void) target; (void) autoRelease; throw_no_ogl(); #else const int kind = arr.kind(); switch (kind) { case _InputArray::OPENGL_BUFFER: case _InputArray::GPU_MAT: copyFrom(arr, target, autoRelease); break; default: { Mat mat = arr.getMat(); CV_Assert( mat.isContinuous() ); const GLsizeiptr asize = mat.rows * mat.cols * mat.elemSize(); impl_.reset(new Impl(asize, mat.data, target, autoRelease)); rows_ = mat.rows; cols_ = mat.cols; type_ = mat.type(); break; } } #endif }
void cv::ocl::oclMat::upload(const Mat &m) { if (!Context::getContext()->supportsFeature(FEATURE_CL_DOUBLE) && m.depth() == CV_64F) { CV_Error(Error::OpenCLDoubleNotSupported, "Selected device doesn't support double"); return; } CV_DbgAssert(!m.empty()); Size wholeSize; Point ofs; m.locateROI(wholeSize, ofs); create(wholeSize, m.type()); if (m.channels() == 3) { int pitch = wholeSize.width * 3 * m.elemSize1(); int tail_padding = m.elemSize1() * 3072; int err; cl_mem temp = clCreateBuffer(*(cl_context*)clCxt->getOpenCLContextPtr(), CL_MEM_READ_WRITE, (pitch * wholeSize.height + tail_padding - 1) / tail_padding * tail_padding, 0, &err); openCLVerifyCall(err); openCLMemcpy2D(clCxt, temp, pitch, m.datastart, m.step, wholeSize.width * m.elemSize(), wholeSize.height, clMemcpyHostToDevice, 3); convert_C3C4(temp, *this); openCLSafeCall(clReleaseMemObject(temp)); } else openCLMemcpy2D(clCxt, data, step, m.datastart, m.step, wholeSize.width * elemSize(), wholeSize.height, clMemcpyHostToDevice); rows = m.rows; cols = m.cols; offset = ofs.y * step + ofs.x * elemSize(); }
cv::Scalar cv::mean( InputArray _src, InputArray _mask ) { Mat src = _src.getMat(), mask = _mask.getMat(); CV_Assert( mask.empty() || mask.type() == CV_8U ); int k, cn = src.channels(), depth = src.depth(); SumFunc func = sumTab[depth]; CV_Assert( cn <= 4 && func != 0 ); const Mat* arrays[] = {&src, &mask, 0}; uchar* ptrs[2]; NAryMatIterator it(arrays, ptrs); Scalar s; int total = (int)it.size, blockSize = total, intSumBlockSize = 0; int j, count = 0; AutoBuffer<int> _buf; int* buf = (int*)&s[0]; bool blockSum = depth <= CV_16S; size_t esz = 0, nz0 = 0; if( blockSum ) { intSumBlockSize = depth <= CV_8S ? (1 << 23) : (1 << 15); blockSize = std::min(blockSize, intSumBlockSize); _buf.allocate(cn); buf = _buf; for( k = 0; k < cn; k++ ) buf[k] = 0; esz = src.elemSize(); } for( size_t i = 0; i < it.nplanes; i++, ++it ) { for( j = 0; j < total; j += blockSize ) { int bsz = std::min(total - j, blockSize); int nz = func( ptrs[0], ptrs[1], (uchar*)buf, bsz, cn ); count += nz; nz0 += nz; if( blockSum && (count + blockSize >= intSumBlockSize || (i+1 >= it.nplanes && j+bsz >= total)) ) { for( k = 0; k < cn; k++ ) { s[k] += buf[k]; buf[k] = 0; } count = 0; } ptrs[0] += bsz*esz; if( ptrs[1] ) ptrs[1] += bsz; } } return s*(nz0 ? 1./nz0 : 0); }
void wrapCVMat(Mat& cvMat, image_t& img) { img.height = cvMat.rows; img.width = cvMat.cols; img.depth = cvMat.channels(); img.pitch = cvMat.cols*cvMat.elemSize(); img.itemSize = cvMat.elemSize1(); img.data = cvMat.ptr(); }
/** * This is the streaming server, run as separate thread */ void* streamServer(void* arg) { struct sockaddr_in serverAddr, clientAddr; socklen_t clientAddrLen = sizeof(clientAddr); /* make this thread cancellable using pthread_cancel() */ pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); if ((listenSock = socket(PF_INET, SOCK_STREAM, 0)) < 0) { quit("socket() failed.", 1); } serverAddr.sin_family = PF_INET; serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); serverAddr.sin_port = htons(listenPort); if (bind(listenSock, (sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { quit("bind() failed", 1); } if (listen(listenSock, 5) == -1) { quit("listen() failed.", 1); } int imgSize = img.total()*img.elemSize(); char sockData[imgSize]; int bytes=0; /* start receiving images */ while(1) { cout << "-->Waiting for TCP connection on port " << listenPort << " ...nn"; /* accept a request from a client */ if ((connectSock = accept(listenSock, (sockaddr*)&clientAddr, &clientAddrLen)) == -1) { quit("accept() failed", 1); }else{ cout << "-->Receiving image from " << inet_ntoa(clientAddr.sin_addr) << ":" << ntohs(clientAddr.sin_port) << "..." << endl; } memset(sockData, 0x0, sizeof(sockData)); while(1){ for (int i = 0; i < imgSize; i += bytes) { if ((bytes = recv(connectSock, sockData +i, imgSize - i, 0)) == -1) { quit("recv failed", 1); } } /* convert the received data to OpenCV's Mat format, thread safe */ pthread_mutex_lock(&mutex); for (int i = 0; i < img.rows; i++) { for (int j = 0; j < img.cols; j++) { (img.row(i)).col(j) = (uchar)sockData[((img.cols)*i)+j]; } } is_data_ready = 1; memset(sockData, 0x0, sizeof(sockData)); pthread_mutex_unlock(&mutex); } } /* have we terminated yet? */ pthread_testcancel(); /* no, take a rest for a while */ usleep(1000); }
bool initUDPFetcher(bool debug) { /////////////////////////////////UDP Initialization/////////////////////////////////// DBG = debug; struct sockaddr_in addr; sockfd=socket(AF_INET,SOCK_DGRAM,0); if(sockfd<0) { fprintf(stderr,"Socket Error:%s\n",strerror(errno)); return false; } bzero(&addr,sizeof(struct sockaddr_in)); addr.sin_family=AF_INET; addr.sin_addr.s_addr=htonl(INADDR_ANY); addr.sin_port=htons(SERVER_PORT); if(bind(sockfd,(struct sockaddr *)&addr,sizeof(struct sockaddr_in))<0) { fprintf(stderr,"Bind Error:%s\n",strerror(errno)); return false; } /////////////////////////////////Image Initialization/////////////////////////////// imgSize = image_left.total()*image_left.elemSize(); //calculate image size if(DBG) cout<<"image size is "<< imgSize <<endl; k_times = imgSize / MAX_PKG_SIZE; if(DBG) cout << k_times << endl; //////////////////////////////////multithread stuff/////////////////////////////// enableUDPImageFetcher(true); errorT = pthread_create(&tid_left, NULL, fetchImageLeft, NULL); if(errorT){ printf("pthread Left is not created...\n"); return false; } errorT = pthread_create(&tid_right, NULL, fetchImageRight, NULL); if(errorT){ printf("pthread Right is not created...\n"); return false; } return true; }
static void paintPixel(Mat &img, int c, int r) { if(r > 720){ debug("r:%d\n", r); ASSERT(false); } uchar *data = img.data + r*img.step + c*img.elemSize(); *data = 200; }
int main(int argc, char** argv) { //********************************************************************** //-- Network code ------------------------------------------------------ //********************************************************************** int sokt; char* serverIP; int serverPort; serverIP = argv[1]; serverPort = atoi(argv[2]); struct sockaddr_in serverAddr; socklen_t addrLen = sizeof(struct sockaddr_in); if ((sokt = socket(PF_INET, SOCK_STREAM, 0)) < 0) exit(1); serverAddr.sin_family = PF_INET; serverAddr.sin_addr.s_addr = inet_addr(serverIP); serverAddr.sin_port = htons(serverPort); if (connect(sokt, (sockaddr*)&serverAddr, addrLen) < 0) exit(1); //********************************************************************** //-- OpenCV code ------------------------------------------------------- //********************************************************************** Mat img; img = Mat::zeros(480 , 640, CV_8U); int imgSize = img.total() * img.elemSize(); uchar *iptr = img.data; int bytes = 0; int key; if (!img.isContinuous()) img = img.clone(); namedWindow("CV Video Client",1); while (key != 'q') { if ((bytes = recv(sokt, iptr, imgSize , MSG_WAITALL)) == -1) exit(1); cv::imshow("CV Video Client", img); if (key = cv::waitKey(10) >= 0) break; } close(sokt); return 0; }
int save_result(const char* output_path, Mat& cameraMatrix, Mat& distCoeffs) { time_t now; struct tm *timenow; char name1[200]; char name2[200]; char time_str[50]; time(&now); timenow = localtime(&now); printf("Local time is %s \n",asctime(timenow)); sprintf(time_str, "%d_%d_%d_%d_%d", timenow->tm_year + 1900, timenow->tm_mon, timenow->tm_mday, timenow->tm_hour, timenow->tm_min); sprintf(name1, "%s/camera_%s.data", output_path, time_str); sprintf(name2, "%s/camera_%s.yml", output_path, time_str); FILE* pSave = fopen(name1, "w"); if(pSave != NULL) { cout << cameraMatrix<<endl; cout << distCoeffs<<endl; fwrite(cameraMatrix.data, cameraMatrix.elemSize(), cameraMatrix.cols*cameraMatrix.rows, pSave); fwrite(distCoeffs.data, distCoeffs.elemSize(), distCoeffs.cols*distCoeffs.rows, pSave); printf("size_t of cameraMatrix = %d size_t of distCoeffs = %d \n", cameraMatrix.elemSize(), distCoeffs.elemSize()); fclose(pSave); } cv::FileStorage fs(name2, FileStorage::WRITE); fs <<"cameraMatrix"<<cameraMatrix; fs <<"distCoeffs"<<distCoeffs; return 0; }
virtual void execute(MachineState * ms) { AnimationState target = ms->config.targetAnimationState; AnimationState current = ms->config.currentAnimationState; int value = current.value; string emotion = current.emotion; if (target.emotion == current.emotion) { // we're in the same emotion if (target.value == current.value) { return; } if (target.value > current.value) { value++; } else { value--; } } else { // different emotion; head towards 0 and then switch if (current.value == 0) { // if we're at 0, switch to the new emotion emotion = target.emotion; value = 0; } else { // otherwise, keep heading back towards neutral value--; } } AnimationState nextState = {emotion, value}; int index = ms->config.emotionIndex[emotion]; Mat image = ms->config.emotionImages[index][value]; if (isSketchyMat(image)) { cout << "ChangeAnimationState: cannot load " << emotion << " " << value << endl; return; } else { sensor_msgs::Image msg; msg.header.stamp = ros::Time::now(); msg.width = image.cols; msg.height = image.rows; msg.step = image.cols * image.elemSize(); msg.is_bigendian = false; msg.encoding = sensor_msgs::image_encodings::BGR8; msg.data.assign(image.data, image.data + size_t(image.rows * msg.step)); ms->config.baxterConfig->face_screen_pub.publish(msg); } ms->config.currentAnimationState = nextState; std::stringstream program; double seconds = 1/ms->config.animationRate; program << seconds << " spinForSeconds changeAnimationState"; ms->evaluateProgram(program.str()); }
void cv::ocl::oclMat::upload(const Mat &m) { CV_DbgAssert(!m.empty()); Size wholeSize; Point ofs; m.locateROI(wholeSize, ofs); // int type = m.type(); // if(m.oclchannels() == 3) //{ // type = CV_MAKETYPE(m.depth(), 4); //} create(wholeSize, m.type()); if(m.channels() == 3) { int pitch = wholeSize.width * 3 * m.elemSize1(); int tail_padding = m.elemSize1() * 3072; int err; cl_mem temp = clCreateBuffer((cl_context)clCxt->oclContext(), CL_MEM_READ_WRITE, (pitch * wholeSize.height + tail_padding - 1) / tail_padding * tail_padding, 0, &err); openCLVerifyCall(err); openCLMemcpy2D(clCxt, temp, pitch, m.datastart, m.step, wholeSize.width * m.elemSize(), wholeSize.height, clMemcpyHostToDevice, 3); convert_C3C4(temp, *this); //int* cputemp=new int[wholeSize.height*wholeSize.width * 3]; //int* cpudata=new int[this->step*this->wholerows/sizeof(int)]; //openCLSafeCall(clEnqueueReadBuffer(clCxt->impl->clCmdQueue, temp, CL_TRUE, // 0, wholeSize.height*wholeSize.width * 3* sizeof(int), cputemp, 0, NULL, NULL)); //openCLSafeCall(clEnqueueReadBuffer(clCxt->impl->clCmdQueue, (cl_mem)data, CL_TRUE, // 0, this->step*this->wholerows, cpudata, 0, NULL, NULL)); //for(int i=0;i<wholeSize.height;i++) //{ // int *a = cputemp+i*wholeSize.width * 3,*b = cpudata + i*this->step/sizeof(int); // for(int j=0;j<wholeSize.width;j++) // { // if((a[3*j] != b[4*j])||(a[3*j+1] != b[4*j+1])||(a[3*j+2] != b[4*j+2])) // printf("rows=%d,cols=%d,cputtemp=%d,%d,%d;cpudata=%d,%d,%d\n", // i,j,a[3*j],a[3*j+1],a[3*j+2],b[4*j],b[4*j+1],b[4*j+2]); // } //} //delete []cputemp; //delete []cpudata; openCLSafeCall(clReleaseMemObject(temp)); } else { openCLMemcpy2D(clCxt, data, step, m.datastart, m.step, wholeSize.width * elemSize(), wholeSize.height, clMemcpyHostToDevice); } rows = m.rows; cols = m.cols; offset = ofs.y * step + ofs.x * elemSize(); //download_channels = m.channels(); }
static void cb_need_data (GstElement *appsrc, guint unused_size, gpointer user_data) { //static gboolean white = FALSE; g_print("\nmain loop:cb_need_data Iteration:%d \n",framecount); static gboolean white = FALSE; static GstClockTime timestamp = 0; GstBuffer* buffer; GstBuffer* newbuffer; gsize size; gsize amount; GstFlowReturn ret; Mat image; sprintf(imagename,"image_%08d.png",framecount); framecount++; image = imread(imagename, CV_LOAD_IMAGE_COLOR); if(!image.data) { g_print("%s is not readable!\n",imagename); g_main_loop_quit (loop); g_print("g_main_loop_quit done\n"); return ; } g_print("%s is loaded!\n",imagename); size = image.rows * image.cols * image.elemSize(); g_print("image.rows = %d, image.cols = %d, image.elemSize = %lu \n", image.rows, image.cols, image.elemSize()); buffer = gst_buffer_new_allocate (NULL, size, NULL); amount = gst_buffer_fill(buffer, 0, image.data, size); g_print("gst_buffer_new_fill filled %lu bytes.\n",amount); GST_BUFFER_PTS (buffer) = timestamp; GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale_int (1, GST_SECOND, 2); timestamp += GST_BUFFER_DURATION (buffer); g_signal_emit_by_name (appsrc, "push-buffer", buffer, &ret); g_print("g_signal_emit_by_name done\n\n"); if (ret != GST_FLOW_OK) { /* something wrong, stop pushing */ g_print("something wrong, stop pushing.\n"); g_main_loop_quit (loop); g_print("g_main_loop_quit done\n"); } }
bool RBaseStream::open( const Mat& buf ) { close(); if( buf.empty() ) return false; CV_Assert(buf.isContinuous()); m_start = buf.data; m_end = m_start + buf.cols*buf.rows*buf.elemSize(); m_allocated = false; m_is_opened = true; setPos(0); return true; }
void printImageFeatures( const Mat &imagem ) { cout << endl; cout << "Numero de linhas : " << imagem.size().height << endl; cout << "Numero de colunas : " << imagem.size().width << endl; cout << "Numero de canais : " << imagem.channels() << endl; cout << "Numero de bytes por pixel : " << imagem.elemSize() << endl; cout << endl; }
void cv::GlBuffer::Impl::copyFrom(const Mat& m, unsigned int target) { CV_Assert(buffer_ != 0); CV_Assert(m.isContinuous()); bind(target); size_t size = m.rows * m.cols * m.elemSize(); glFuncTab()->bufferSubData(target, 0, size, m.data); CV_CheckGlError(); unbind(target); }
DLLEXPORT MyMat* LoadFromCIFAR10Cal(string path) { MyMat* imgs = new MyMat[50000]; int planeId[3]={2,1,0}; int width=32; int height=32; int type=CV_8UC3; int imgSize=width*height; int nChannels=3; int imgDataSize = 1+imgSize*nChannels; Mat kernel = (Mat_<float>(3, 3) << 0, -1, 0, -1, 5, -1, 0, -1, 0); Mat img; Mat rs; for(int m = 0; m < 5; m++) { int n = 0; ifstream fin(path + "data_batch_" + char(m + '1') +".bin", ios::binary); //使用构造函数创建矩阵 while(fin.eof() != true) { if(n >= 10000) break; img.create(width, height, type); rs.create(64, 64, type); imgs[m * 10000 + n].create(64, 64, type); uchar *buf=(uchar*)calloc(imgDataSize,sizeof(uchar)); fin.read((char *)buf,(imgDataSize)*sizeof(uchar)); imgs[m * 10000 + n].type = buf[0]; imgs[m * 10000 + n].id = m * 10000 + n; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++ ) { //uchar* dataIJ = imgs[m * 10000 + n].data + i * imgs[m * 10000 + n].step + j * imgs[m * 10000 + n].elemSize(); uchar* dataIJ = img.data + i * img.step + j * img.elemSize();// img.at(i, j) for(int k = 0; k < nChannels; k++) dataIJ[k] = buf[1 + planeId[k] * imgSize + i * width + j]; } } //拉普拉斯锐化 resize(img, rs, rs.size(), 0, 0, INTER_CUBIC); filter2D(rs, imgs[m * 10000 + n], rs.depth(), kernel ); n++; free(buf); } fin.close(); } return imgs; }
void cv::ogl::Buffer::copyTo(OutputArray arr, Target target, bool autoRelease) const { #ifndef HAVE_OPENGL (void) arr; (void) target; (void) autoRelease; throw_nogl(); #else const int kind = arr.kind(); switch (kind) { case _InputArray::OPENGL_BUFFER: { arr.getOGlBufferRef().copyFrom(*this, target, autoRelease); break; } case _InputArray::OPENGL_TEXTURE: { arr.getOGlTexture2DRef().copyFrom(*this, autoRelease); break; } case _InputArray::GPU_MAT: { #if !defined HAVE_CUDA || defined(CUDA_DISABLER) throw_nocuda(); #else GpuMat& dmat = arr.getGpuMatRef(); dmat.create(rows_, cols_, type_); impl_->copyTo(dmat.data, dmat.step, dmat.cols * dmat.elemSize(), dmat.rows); #endif break; } default: { arr.create(rows_, cols_, type_); Mat mat = arr.getMat(); CV_Assert( mat.isContinuous() ); impl_->copyTo(mat.rows * mat.cols * mat.elemSize(), mat.data); } } #endif }
void repeat(const Mat& src, int ny, int nx, Mat& dst) { dst.create(src.rows*ny, src.cols*nx, src.type()); Size ssize = src.size(), dsize = dst.size(); int esz = (int)src.elemSize(); int x, y; ssize.width *= esz; dsize.width *= esz; for( y = 0; y < ssize.height; y++ ) { for( x = 0; x < dsize.width; x += ssize.width ) memcpy( dst.data + y*dst.step + x, src.data + y*src.step, ssize.width ); } for( ; y < dsize.height; y++ ) memcpy( dst.data + y*dst.step, dst.data + (y - ssize.height)*dst.step, dsize.width ); }
void flip( InputArray _src, OutputArray _dst, int flip_mode ) { Mat src = _src.getMat(); CV_Assert( src.dims <= 2 ); _dst.create( src.size(), src.type() ); Mat dst = _dst.getMat(); size_t esz = src.elemSize(); if( flip_mode <= 0 ) flipVert( src.data, src.step, dst.data, dst.step, src.size(), esz ); else flipHoriz( src.data, src.step, dst.data, dst.step, src.size(), esz ); if( flip_mode < 0 ) flipHoriz( dst.data, dst.step, dst.data, dst.step, dst.size(), esz ); }
TEST(Highgui_Tiff, write_read_16bit_big_little_endian) { // see issue #2601 "16-bit Grayscale TIFF Load Failures Due to Buffer Underflow and Endianness" // Setup data for two minimal 16-bit grayscale TIFF files in both endian formats uchar tiff_sample_data[2][86] = { { // Little endian 0x49, 0x49, 0x2a, 0x00, 0x0c, 0x00, 0x00, 0x00, 0xad, 0xde, 0xef, 0xbe, 0x06, 0x00, 0x00, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x11, 0x01, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x17, 0x01, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00 }, { // Big endian 0x4d, 0x4d, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x0c, 0xde, 0xad, 0xbe, 0xef, 0x00, 0x06, 0x01, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x01, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x10, 0x00, 0x00, 0x01, 0x06, 0x00, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x11, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x01, 0x17, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04 } }; // Test imread() for both a little endian TIFF and big endian TIFF for (int i = 0; i < 2; i++) { string filename = cv::tempfile(".tiff"); // Write sample TIFF file FILE* fp = fopen(filename.c_str(), "wb"); ASSERT_TRUE(fp != NULL); ASSERT_EQ((size_t)1, fwrite(tiff_sample_data, 86, 1, fp)); fclose(fp); Mat img = imread(filename, IMREAD_UNCHANGED); EXPECT_EQ(1, img.rows); EXPECT_EQ(2, img.cols); EXPECT_EQ(CV_16U, img.type()); EXPECT_EQ(sizeof(ushort), img.elemSize()); EXPECT_EQ(1, img.channels()); EXPECT_EQ(0xDEAD, img.at<ushort>(0,0)); EXPECT_EQ(0xBEEF, img.at<ushort>(0,1)); remove(filename.c_str()); } }
void flip( const Mat& src, Mat& dst, int flip_mode ) { static FlipHorizFunc tab[] = { 0, flipHoriz_<uchar>, // 1 flipHoriz_<ushort>, // 2 flipHoriz_<Vec<uchar,3> >, // 3 flipHoriz_<int>, // 4 0, flipHoriz_<Vec<ushort,3> >, // 6 0, flipHoriz_<int64>, // 8 0, 0, 0, flipHoriz_<Vec<int,3> >, // 12 0, 0, 0, flipHoriz_<Vec<int64,2> >, // 16 0, 0, 0, 0, 0, 0, 0, flipHoriz_<Vec<int64,3> >, // 24 0, 0, 0, 0, 0, 0, 0, flipHoriz_<Vec<int64,4> > // 32 }; dst.create( src.size(), src.type() ); if( flip_mode == 0 ) flipVert( src, dst ); else { int esz = (int)src.elemSize(); CV_Assert( esz <= 32 ); FlipHorizFunc func = tab[esz]; CV_Assert( func != 0 ); if( flip_mode > 0 ) func( src, dst, false ); else if( src.data != dst.data ) func( src, dst, true ); else { func( dst, dst, false ); flipVert( dst, dst ); } } }