将Mat中的图像转换为BufferedImage

时间:2015-05-15 15:03:01

标签: java swing opencv

我有这个源代码,可以在Mat中打开OpenCv的图像,然后进行一些操作,然后class GetDataFromServer extends AsyncTask<String, String, String> { * */ // Progress Dialog private ProgressDialog qDialog; private Context context; private String dialogString; private ArrayList<String[]> newLoginResult; private String value; // JSON parser class String url_newGame ="http://xxxxxx.php"; public myAsyncMethos(String dialogMessage, Context con) { this.qDialog = new ProgressDialog(con); this.dialogString = dialogMessage; this.context = con; } /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); qDialog = new ProgressDialog(this.context); qDialog.setMessage(this.dialogString); qDialog.setIndeterminate(false); qDialog.setCancelable(false); qDialog.show(); } @Override protected JSONObject doInBackground(String... args) { //MAKE SERVER CALL and cast to JSONOBject return jsonNewUser; } public void onPostExecute(JSONObject jsonString) { // dismiss the dialog after getting response qDialog.dismiss(); value = "Whatever you want"; } public void setValue(String value){ this.value=value; } public String getValue(){ return this.value; } }` 应该将其转换为图像,以便它可以在JFrame中显示。但我无法弄清楚如何传递参数。

bufferedImage

1 个答案:

答案 0 :(得分:4)

这是我们前一段时间用于2.4.8或.9的一些代码。让我知道它是否适合你。

我认为当我们尝试传入现有的BufferedImage时,我们可能遇到了一些问题,但如果你为BufferedImage传入null,它可以正常工作。

/**  
 * Converts/writes a Mat into a BufferedImage.  
 *  
 * @param matrix Mat of type CV_8UC3 or CV_8UC1  
 * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY  
 */  
public static BufferedImage matToBufferedImage(Mat matrix, BufferedImage bimg)
{
    if ( matrix != null ) { 
        int cols = matrix.cols();  
        int rows = matrix.rows();  
        int elemSize = (int)matrix.elemSize();  
        byte[] data = new byte[cols * rows * elemSize];  
        int type;  
        matrix.get(0, 0, data);  
        switch (matrix.channels()) {  
        case 1:  
            type = BufferedImage.TYPE_BYTE_GRAY;  
            break;  
        case 3:  
            type = BufferedImage.TYPE_3BYTE_BGR;  
            // bgr to rgb  
            byte b;  
            for(int i=0; i<data.length; i=i+3) {  
                b = data[i];  
                data[i] = data[i+2];  
                data[i+2] = b;  
            }  
            break;  
        default:  
            return null;  
        }  

        // Reuse existing BufferedImage if possible
        if (bimg == null || bimg.getWidth() != cols || bimg.getHeight() != rows || bimg.getType() != type) {
            bimg = new BufferedImage(cols, rows, type);
        }        
        bimg.getRaster().setDataElements(0, 0, cols, rows, data);
    } else { // mat was null
        bimg = null;
    }
    return bimg;  
}