Get Image Size using OpenCV

Get Image Size using OpenCV

During image processing, it is often necessary to know the image size such as width, height, and number of the channels. This tutorial provides example how to get image size using OpenCV.

When the image is loaded, it is stored in an n-dimensional numerical single-channel or multichannel array depending on image type, such as grayscale or color image. Use the following code to get image width, height, and number of the channels:

import cv2

img = cv2.imread('test.jpg')
width = img.shape[1]
height = img.shape[0]
channels = img.shape[2] if img.ndim > 2 else 1

print(width, height, channels)
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main()
{
    Mat img = imread("test.jpg");
    int width = img.cols;
    int height = img.rows;
    int channels = img.channels();

    std::cout << width << ' ' << height << ' ' << channels << std::endl;

    return 0;
}
package app;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;

public class Main
{
    static { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }

    public static void main(String[] args)
    {
        Mat img = Imgcodecs.imread("test.jpg");
        int width = img.cols();
        int height = img.rows();
        int channels = img.channels();

        System.out.println(width + " " + height + " " + channels);

        System.exit(0);
    }
}

Output example:

640 480 3

Leave a Comment

Cancel reply

Your email address will not be published.