2017-02-22 2 views
1

Java에서 Opencv를 처음 사용했습니다. 나는 Mat 이미지가 있고 특정 영역에서 픽셀을 읽으려고하고 있으므로 나중에 해당 영역을 반복하여 HSV를 결정할 수 있습니다. CvRect을 사용하여 좌표 및 크기를 얻으려고합니다. 영상. 이미지의 해당 영역을 어떻게 얻을 수 있습니까? 하나 픽셀 하나를 읽거나 전체 이미지에 대한 자바으로 구형의 모든 픽셀을 얻을하고 큰 배열 작업 :매트 이미지의 픽셀 영역을 얻는 방법

Mat firstImage = Imgcodecs.imread("firstImage.png"); 
    CvRect topL = new CvRect(firstImage.get(160, 120, 30, 30)); 

답변

1

는 두 가지 방법이 있습니다. 어떤 것이 가장 좋은지는 rect가 얼마나 큰가에 달려 있습니다. 아래의 코드는 이미지의 지정된 rect 부분을 Java 배열로 먼저 가져옵니다.

import java.awt.Color; 
import org.opencv.core.Core; 
import org.opencv.core.Mat; 
import org.opencv.core.Rect; 
import org.opencv.highgui.Highgui; 

public class OpenCVThing 
{ 
    public static void main(String[] args) 
    { 
     String opencvpath = System.getProperty("user.dir") + "\\lib\\"; 
     System.load(opencvpath + Core.NATIVE_LIBRARY_NAME + ".dll"); 
     // Get the whole rect into smallImg 
     Mat firstImage = Highgui.imread("capture.png"); 
     System.out.println("total pxels:" + firstImage.total()); 
     // We are getting a column 30 high and 30 wide 
     int width = 30; 
     int height = 30; 
     Rect roi = new Rect(120, 160, width, height); 
     Mat smallImg = new Mat(firstImage, roi); 
     int channels = smallImg.channels(); 
     System.out.println("small pixels:" + smallImg.total()); 
     System.out.println("channels:" + smallImg.channels()); 
     int totalBytes = (int)(smallImg.total() * smallImg.channels()); 
     byte buff[] = new byte[totalBytes]; 
     smallImg.get(0, 0, buff); 

     // assuming it's of CV_8UC3 == BGR, 3 byte/pixel 
     // Effectively assuming channels = 3 
     for (int i=0; i< height; i++) 
     { 
      // stride is the number of bytes in a row of smallImg 
      int stride = channels * width; 
      for (int j=0; j<stride; j+=channels) 
      { 
       int b = buff[(i * stride) + j]; 
       int g = buff[(i * stride) + j + 1]; 
       int r = buff[(i * stride) + j + 2]; 
       float[] hsv = new float[3]; 
       Color.RGBtoHSB(r,g,b,hsv); 
       // Do something with the hsv. 
       System.out.println("hsv: " + hsv[0]); 
      } 
     } 
    } 
} 

주 1 :이 경우, 털의 각 바이트 I의 형식을 가정 했으므로 CV_8UC3이며, 화소의 제 나타낸다.

total pxels:179305 
small pixels:900 
channels:3 
hsv: 0.5833333 
hsv: 0.5833333 
hsv: 0.5833333 
hsv: 0.5833333 
hsv: 0.5833333 

etc ... 

this page를 참조하고 좀 더 자세하게

+0

은'CvRect 수신자 = 새로운 CvRect에 대한 docs (firstImage.get :

코드는 다음과 같은 출력이 답변의 화면 캡처에서 테스트되었다 (160,120,30,30));'실제로 CvRect가 인수로 사용할 수없는 이미지를 얻는 데는 효과가 없다. 나는 그 이미지의 해당 영역을 얻고 싶다는 것을 증명하기 위해 내 질문에 사용했다. – cuber

+0

이미지 나는 내가 사용하고있는 이미지의'CV 형식 '이 비디오 캡처의 프레임에서 이미지를 가져 와서 그 이미지의 값을 얻으려고하는지 확신 할 수 없다. 이것은'mat2Img.getImage (mat2Img.mat);입니다. 이것은 Mat2Image의 Object입니다. – cuber

+0

firstImage.type(); http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat-type에서 유형 중 하나를 나타내는 int를 반환합니다. Java에서 숫자를 변환하는 방법을 잘 모르겠습니다. –

관련 문제