[英]Rotate image using openCV
我正在嘗試旋轉圖像。 基於http://docs.opencv.org/doc/tutorials/imgproc/imgtrans/warp_affine/warp_affine.html,但它不起作用,並且我沒有收到任何錯誤。 可能是什么問題呢 ? 如果有人給我一些建議,我將不勝感激。 這是代碼:
public static void main( String[] args )
{
Mat warp_dst;
Point [] srcTri = new Point[3];
Point [] dstTri = new Point[3];
MatOfPoint2f srcPoints;
MatOfPoint2f dstPoints;
Mat warpMat;
try {
System.loadLibrary( Core.NATIVE_LIBRARY_NAME );
File input = new File("C:\\Users\\Samsung\\Desktop\\res\\drawable-nodpi\\test.jpg");
BufferedImage image = ImageIO.read(input);
byte[] data = ((DataBufferByte) image.getRaster().
getDataBuffer()).getData();
Mat mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC3);
mat.put(0, 0, data);
Mat mat1 = new Mat(image.getHeight(),image.getWidth(),CvType.CV_8UC1);
Imgproc.cvtColor(mat, mat1, Imgproc.COLOR_RGB2GRAY);
byte[] data1 = new byte[mat1.rows()*mat1.cols()*(int)(mat1.elemSize())];
mat1.get(0, 0, data1);
BufferedImage image1=new BufferedImage(mat1.cols(),mat1.rows()
,BufferedImage.TYPE_BYTE_GRAY);
image1.getRaster().setDataElements(0,0,mat1.cols(),mat1.rows(),data1);
warp_dst = Mat.zeros(mat1.rows(), mat1.cols(), mat1.type());
srcTri[0] = new Point(0,0);
srcTri[1] = new Point(mat1.cols() -1 , 0 );
srcTri[2] = new Point(0, mat1.rows()- 1);
dstTri[0] = new Point( mat1.cols()*0.0, mat1.rows()*0.33);
dstTri[1] = new Point( mat1.cols()*0.85, mat1.rows()*0.25);
dstTri[2] = new Point( mat1.cols()*0.15, mat1.rows()*0.7);
srcPoints = new MatOfPoint2f(srcTri);
dstPoints = new MatOfPoint2f(dstTri);
warpMat = Imgproc.getAffineTransform(srcPoints, dstPoints);
Imgproc.warpAffine(mat1, warp_dst, warpMat, warp_dst.size());
byte[] data2 = new byte[warp_dst.rows()*warp_dst.cols()*(int)(warp_dst.elemSize())];
mat1.get(0, 0, data2);
BufferedImage image2=new BufferedImage(warp_dst.cols(),warp_dst.rows()
,BufferedImage.TYPE_BYTE_GRAY);
image2.getRaster().setDataElements(0,0,warp_dst.cols(),warp_dst.rows(),data1);
File ouptut = new File("C:\\Users\\Samsung\\Desktop\\res\\drawable-nodpi\\grayscale5.jpg");
ImageIO.write(image2, "jpg", ouptut);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
有一種更簡單的旋轉圖像的方法。 代碼在C中,但是您可以使用相同的方法
void rotate(cv::Mat& src, double angle, cv::Mat& dst)
{
int len = std::max(src.cols, src.rows);
cv::Point2f pt(len/2., len/2.);
cv::Mat r = cv::getRotationMatrix2D(pt, angle, 1.0);
cv::warpAffine(src, dst, r, cv::Size(len, len));
}
我檢查了它的好奇心,不得不做一些錯誤,因為它也不起作用..(我得到了不變的圖像)。 有沒有人在Java,Android中有旋轉圖片的有效示例? (在C中沒有問題。)
warp_dst = Mat.zeros(image.getHeight(),image.getWidth(), image.getType());
Point pt = new Point(mat1.cols()/2, mat1.rows()/2);
Mat M = Imgproc.getRotationMatrix2D(pt, 30, 1.0);
Imgproc.warpAffine( mat1, warp_dst, M, mat1.size());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.