Image scaling and rotating in C/C++

前端 未结 10 1626
情深已故
情深已故 2020-11-29 07:55

What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level fro

10条回答
  •  清歌不尽
    2020-11-29 08:16

    It has not been mentioned yet, so I will point out that OpenCV has functions for scaling and rotating images, as well as an enormous number of other utilities. It may contain many features that are not relevant to the question, but it is very easy to setup and use for a library of its kind.

    You can try to implement transformations like this manually, but the simple approach to scaling and rotating will generally result in a significant loss of detail.

    Using OpenCV, scaling can be done like so:

    float scaleFactor = 0.68f;
    cv::Mat original = cv::imread(path);
    cv::Mat scaled;
    cv::resize(original, scaled, cv::Size(0, 0), scaleFactor, scaleFactor, cv::INTER_LANCZOS4);
    cv::imwrite("new_image.jpg", scaled);
    

    This scales the image down by a factor of 0.68 using Lanczos interpolation.

    I am not as familiar with rotations, but here's part of an example from one of the tutorials on the OpenCV website that I have edited down to the relevant parts. (The original had skew and translation in it also...)

    /// Compute a rotation matrix with respect to the center of the image
    Point center = Point(original.size().width / 2, original.size().height / 2);
    double angle = -50.0;
    double scale = 0.6;
    
    /// Get the rotation matrix with the specifications above
    Mat rot_mat( 2, 3, CV_32FC1 );
    rot_mat = getRotationMatrix2D(center, angle, scale);
    
    /// Rotate the image
    Mat rotated_image;
    warpAffine(src, rotated_image, rot_mat, src.size());
    

    OpenCV Website

    They have some very nice documentation too.

提交回复
热议问题