문제

OpenCV CVloadImage 및 CvsaveImage의 두 기능은 파일 경로를 인수로 받아들입니다.

예를 들어, 이미지를 저장할 때는 다음과 같습니다 cvsaveImage ( "/tmp/output.jpg", dstipl) 그리고 그것은 디스크에 씁니다.

이미 메모리에 버퍼를 공급하는 방법이 있습니까? 따라서 디스크 쓰기 대신 출력 이미지가 메모리에 있습니다.

또한 CVSaveImage와 CVloadImage (메모리 버퍼에 읽고 쓰기)에 대해 이것을 알고 싶습니다. 감사!


내 목표는 인코딩 된 (JPEG) 버전의 파일을 메모리에 저장하는 것입니다. CVloadImage에도 마찬가지입니다. 메모리에있는 JPEG를 iPlimage 형식으로로드하고 싶습니다.

도움이 되었습니까?

해결책

Libary의 SVN 버전에는 문서화되지 않은 몇 가지 기능이 있습니다.

CV_IMPL CvMat* cvEncodeImage( const char* ext, 
                              const CvArr* arr, const int* _params )

CV_IMPL IplImage* cvDecodeImage( const CvMat* _buf, int iscolor )

최신 체크인 메시지에 따르면 BMP, PNG, PPM 및 TIFF (인코딩 만)에 대한 기본 인코딩/디코딩에 대한 것입니다.

또는 표준 이미지 인코딩 라이브러리 (예 : LIBJPEG)를 사용하고 인코딩 라이브러리의 입력 구조와 일치하도록 iPlimage에서 데이터를 조작 할 수 있습니다.

다른 팁

이것은 나를 위해 효과가있었습니다

// decode jpg (or other image from a pointer)
// imageBuf contains the jpg image
    cv::Mat imgbuf = cv::Mat(480, 640, CV_8U, imageBuf);
    cv::Mat imgMat = cv::imdecode(imgbuf, CV_LOAD_IMAGE_COLOR);
// imgMat is the decoded image

// encode image into jpg
    cv::vector<uchar> buf;
    cv::imencode(".jpg", imgMat, buf, std::vector<int>() );
// encoded image is now in buf (a vector)
    imageBuf = (unsigned char *) realloc(imageBuf, buf.size());
    memcpy(imageBuf, &buf[0], buf.size());
//  size of imageBuf is buf.size();

C ++ 대신 C 버전에 대해 질문을 받았습니다.

#include <opencv/cv.h>
#include <opencv/highgui.h>

int
main(int argc, char **argv)
{
    char *cvwin = "camimg";

    cvNamedWindow(cvwin, CV_WINDOW_AUTOSIZE);

    // setup code, initialization, etc ...
    [ ... ]

    while (1) {      
        // getImage was my routine for getting a jpeg from a camera
        char *img = getImage(fp);
        CvMat mat;

   // substitute 640/480 with your image width, height 
        cvInitMatHeader(&mat, 640, 480, CV_8UC3, img, 0);
        IplImage *cvImg = cvDecodeImage(&mat, CV_LOAD_IMAGE_COLOR);
        cvShowImage(cvwin, cvImg);
        cvReleaseImage(&cvImg);
        if (27 == cvWaitKey(1))         // exit when user hits 'ESC' key
        break;
    }

    cvDestroyWindow(cvwin);
}

나는 당신이 Linux에서 일하고 있다고 가정합니다. libjpeg.doc에서 :

JPEG 압축 작업의 대략적인 개요는 다음과 같습니다.
JPEG 압축 객체를 할당하고 초기화합니다
압축 데이터의 대상을 지정하십시오 (예 : 파일)
이미지 크기 및 색상 공간을 포함하여 압축에 대한 매개 변수 설정

JPEG_START_COMPRES (...);
동안 (스캔 라인이 계속 작성 될 것임)
JPEG_WRITE_SCANLINES (...);

JPEG_FINISH_COMPRES (...);
JPEG 압축 객체를 해제하십시오

당신이하고 싶은 일을하기위한 진정한 트릭은 JPEGLIB.H에 정의 된 사용자 정의 "데이터 대상 (또는 소스) 관리자"를 제공하는 것입니다.

struct jpeg_destination_mgr {
  JOCTET * next_output_byte;    /* => next byte to write in buffer */
  size_t free_in_buffer;        /* # of byte spaces remaining in buffer */

  JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  JMETHOD(void, term_destination, (j_compress_ptr cinfo));
};

기본적으로 소스 및/또는 대상이 원하는 메모리 버퍼가되도록 설정하고 가야합니다.

제쳐두고,이 게시물은 훨씬 나아질 수 있지만 libjpeg62 문서는 솔직히 훌륭합니다. apt-get libjpeg62-dev를 읽고 libjpeg.doc를 읽고 example.c를보십시오. 문제가 발생하고 일할 무언가를 얻을 수 없다면 다시 게시하면 누군가가 도울 수있을 것이라고 확신합니다.

메모리 버퍼에서 파일을로드하는 데 필요한 것은 다른 SRC 관리자 (LIBJPEG)입니다. 우분투 8.10에서 다음 코드를 테스트했습니다.

/******************************** First define mem buffer function bodies **************/
<pre>
/*
 * memsrc.c
 *
 * Copyright (C) 1994-1996, Thomas G. Lane.
 * This file is part of the Independent JPEG Group's software.
 * For conditions of distribution and use, see the accompanying README file.
 *
 * This file contains decompression data source routines for the case of
 * reading JPEG data from a memory buffer that is preloaded with the entire
 * JPEG file.  This would not seem especially useful at first sight, but
 * a number of people have asked for it.
 * This is really just a stripped-down version of jdatasrc.c.  Comparison
 * of this code with jdatasrc.c may be helpful in seeing how to make
 * custom source managers for other purposes.
 */

/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
//include "jinclude.h"
include "jpeglib.h"
include "jerror.h"


/* Expanded data source object for memory input */

typedef struct {
  struct jpeg_source_mgr pub;   /* public fields */

  JOCTET eoi_buffer[2];     /* a place to put a dummy EOI */
} my_source_mgr;

typedef my_source_mgr * my_src_ptr;


/*
 * Initialize source --- called by jpeg_read_header
 * before any data is actually read.
 */

METHODDEF(void)
init_source (j_decompress_ptr cinfo)
{
  /* No work, since jpeg_memory_src set up the buffer pointer and count.
   * Indeed, if we want to read multiple JPEG images from one buffer,
   * this *must* not do anything to the pointer.
   */
}


/*
 * Fill the input buffer --- called whenever buffer is emptied.
 *
 * In this application, this routine should never be called; if it is called,
 * the decompressor has overrun the end of the input buffer, implying we
 * supplied an incomplete or corrupt JPEG datastream.  A simple error exit
 * might be the most appropriate response.
 *
 * But what we choose to do in this code is to supply dummy EOI markers
 * in order to force the decompressor to finish processing and supply
 * some sort of output image, no matter how corrupted.
 */

METHODDEF(boolean)
fill_input_buffer (j_decompress_ptr cinfo)
{
  my_src_ptr src = (my_src_ptr) cinfo->src;

  WARNMS(cinfo, JWRN_JPEG_EOF);

  /* Create a fake EOI marker */
  src->eoi_buffer[0] = (JOCTET) 0xFF;
  src->eoi_buffer[1] = (JOCTET) JPEG_EOI;
  src->pub.next_input_byte = src->eoi_buffer;
  src->pub.bytes_in_buffer = 2;

  return TRUE;
}


/*
 * Skip data --- used to skip over a potentially large amount of
 * uninteresting data (such as an APPn marker).
 *
 * If we overrun the end of the buffer, we let fill_input_buffer deal with
 * it.  An extremely large skip could cause some time-wasting here, but
 * it really isn't supposed to happen ... and the decompressor will never
 * skip more than 64K anyway.
 */

METHODDEF(void)
skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
  my_src_ptr src = (my_src_ptr) cinfo->src;

  if (num_bytes > 0) {
    while (num_bytes > (long) src->pub.bytes_in_buffer) {
      num_bytes -= (long) src->pub.bytes_in_buffer;
      (void) fill_input_buffer(cinfo);
      /* note we assume that fill_input_buffer will never return FALSE,
       * so suspension need not be handled.
       */
    }
    src->pub.next_input_byte += (size_t) num_bytes;
    src->pub.bytes_in_buffer -= (size_t) num_bytes;
  }
}


/*
 * An additional method that can be provided by data source modules is the
 * resync_to_restart method for error recovery in the presence of RST markers.
 * For the moment, this source module just uses the default resync method
 * provided by the JPEG library.  That method assumes that no backtracking
 * is possible.
 */


/*
 * Terminate source --- called by jpeg_finish_decompress
 * after all data has been read.  Often a no-op.
 *
 * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
 * application must deal with any cleanup that should happen even
 * for error exit.
 */

METHODDEF(void)
term_source (j_decompress_ptr cinfo)
{
  /* no work necessary here */
}


/*
 * Prepare for input from a memory buffer.
 */

GLOBAL(void)
jpeg_memory_src (j_decompress_ptr cinfo, const JOCTET * buffer, size_t bufsize)
{
  my_src_ptr src;

  /* The source object is made permanent so that a series of JPEG images
   * can be read from a single buffer by calling jpeg_memory_src
   * only before the first one.
   * This makes it unsafe to use this manager and a different source
   * manager serially with the same JPEG object.  Caveat programmer.
   */
  if (cinfo->src == NULL) { /* first time for this JPEG object? */
    cinfo->src = (struct jpeg_source_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
                  SIZEOF(my_source_mgr));
  }

  src = (my_src_ptr) cinfo->src;
  src->pub.init_source = init_source;
  src->pub.fill_input_buffer = fill_input_buffer;
  src->pub.skip_input_data = skip_input_data;
  src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  src->pub.term_source = term_source;

  src->pub.next_input_byte = buffer;
  src->pub.bytes_in_buffer = bufsize;
}

그런 다음 사용법은 매우 간단합니다. sizeof ()를 sizeof ()로 바꿔야 할 수도 있습니다. 표준 감압 예를 찾으십시오. "JPEG_STDIO_SRC"를 "JPEG_MEMORY_SRC"로 바꾸십시오. 도움이되기를 바랍니다!

다음은 델파이의 예입니다. OpenCV와 함께 사용하기 위해 24 비트 비트 맵을 변환합니다

function BmpToPIplImageEx(Bmp: TBitmap): pIplImage;
Var
  i: Integer;
  offset: LongInt;
  dataByte: PByteArray;  
Begin
  Assert(Bmp.PixelFormat = pf24bit, 'PixelFormat must be 24bit');
  Result := cvCreateImageHeader(cvSize(Bmp.Width, Bmp.Height), IPL_DEPTH_8U, 3);
  cvCreateData(Result);
  for i := 0 to Bmp.height - 1 do
  Begin        
    offset   := longint(Result.imageData) + Result.WidthStep * i;
    dataByte := PByteArray(offset);    
    CopyMemory(dataByte, Bmp.Scanline[i], Result.WidthStep);
  End;
End;

이것은 간접 대답입니다 ...

과거에는 직접 사용했습니다 libpng 그리고 libjpeg 직접이 작업을 수행합니다. 읽기 및 쓰기를 위해 파일 버퍼 대신 메모리 버퍼를 사용할 수있는 충분한 API가 낮습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top