简体   繁体   中英

How to determine pixel intensity with respect to pixel range in x-axis?

I want to see the distribution of a color with respect to image width. That is, if a (black and white) image has width of 720 px, then I want to conclude that a specific range (eg pixels [500,720]) has more white color in compared to rest of the image. What I thought is, I need a slice of the image of 720x1 px, then I need to check the values and distribute them wrt width of 720 px. But I don't know the way I can apply this in a suitable way?

edit: I use OpenCV 4.0.0 with C++.

Example Case: In the first image, it is obvious that right hand side pixels are white. I want to get estimate coordinates of this dense line or zone. The light pink zone is where I am interested in and the red borders are the range where I want to find it.

在此输入图像描述 在此输入图像描述

If you want to get minimum continious range of image columns which contain more white than the rest of the image, than you need first to calculate number of white pixels in each column. Lets assume we have an image 720x500 (500 pixels high and 720 pixels wide). Than you will get an array Arr of 720 elements that equal number of white pixels in each column (1x500) respectively.

const int Width = img.cols;
int* Arr = new int[Width];
for( int x = 0; x < Width; x++ ) {
    Arr[x] = 0;
    for( int y = 0; y < img.rows; y++ ) {
        if ( img.at<cv::Vec3b>(y,x) == cv::Vec3b(255,255,255) ) {
            Arr[x]++;
        }
    }
}

You need to find a minimum range [A;B] in this array that satisfies condition Sum(Arr[0 to A-1]) + Sum(Arr[B+1 to Width-1]) < Sum(Arr[A to B]).

// minimum range width is guaranteed to be less or equal to (Width/2 + 1)
int bestA = 0, minimumWidth = Width/2 + 1;
int total = RangeSum(Arr, 0, Width-1);
for (int i = 0; i < Width; i++) {
    for (int j = i; j < Width && j < i + minimumWidth; j++) {
        int rangeSum = RangeSum(Arr, i, j);
        if (rangeSum > total - rangeSum) { 
            bestA = i; 
            minimumWidth = j - i + 1; 
            break;
        }
    }
}

std::cout << "Most white minimum range - [" << bestA << ";" << bestA + minimumWidth - 1 << "]\n";

You can optimize the code if you precalculate sums for all [0; i] ranges, i from 0 to Width - 1. Than you can calculate RangeSum(Arr, A, B) as PrecalculatedSums[B] - PrecalculatedSums[A] (in O(1) complexity).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM