Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the pixels with highest intensity in OpenCV

Can anyone help me to find out the top 1% (or say top 100 pixels)brightest pixels with their locations of a gray image in opencv. because cvMinMaxLoc() gives only brightest pixel location.

Any help is greatly appreciated.

like image 729
Dark Knight Avatar asked Sep 06 '10 03:09

Dark Knight


3 Answers

this is a simple yet unneficient/stupid way to do it:

for i=1:100
  get brightest pixel using cvMinMaxLoc 
  store location
  set it to a value of zero
end

if you don't mind about efficiency this should work.

you should also check cvInRangeS to find other pixels of similar values defining low and high thresholds.

like image 76
dnul Avatar answered Oct 09 '22 10:10

dnul


You need to calculate the brightness threshold from the histogram. Then you iterate through the pixels to get those positions that are bright enough to satisfy the threshold. The program below instead applies the threshold to the image and displays the result for demonstration purposes:

#!/usr/bin/env python3

import sys
import cv2
import matplotlib.pyplot as plt

if __name__ == '__main__':
    if len(sys.argv) != 2 or any(s in sys.argv for s in ['-h', '--help', '-?']):
        print('usage: {} <img>'.format(sys.argv[0]))
        exit()
    img = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)
    hi_percentage = 0.01 # we want we the hi_percentage brightest pixels
    # * histogram
    hist = cv2.calcHist([img], [0], None, [256], [0, 256]).flatten()
    # * find brightness threshold
    # here: highest thresh for including at least hi_percentage image pixels,
    #       maybe you want to modify it for lowest threshold with for including
    #       at most hi_percentage pixels
    total_count = img.shape[0] * img.shape[1]  # height * width
    target_count = hi_percentage * total_count # bright pixels we look for
    summed = 0
    for i in range(255, 0, -1):
        summed += int(hist[i])
        if target_count <= summed:
            hi_thresh = i
            break
    else:
        hi_thresh = 0
    # * apply threshold & display result for demonstration purposes:
    filtered_img = cv2.threshold(img, hi_thresh, 0, cv2.THRESH_TOZERO)[1]
    plt.subplot(121)
    plt.imshow(img, cmap='gray')
    plt.subplot(122)
    plt.imshow(filtered_img, cmap='gray')
    plt.axis('off')
    plt.tight_layout()
    plt.show()
like image 27
Lars Avatar answered Oct 09 '22 11:10

Lars


C++ version based upon some of the other ideas posted:

// filter the brightest n pixels from a grayscale img, return a new mat
cv::Mat filter_brightest( const cv::Mat& src, int n ) {

    CV_Assert( src.channels() == 1 );
    CV_Assert( src.type() == CV_8UC1 );

    cv::Mat result={};

    // simple histogram
    std::vector<int> histogram(256,0); 
    for(int i=0; i< int(src.rows*src.cols); ++i) 
        histogram[src.at<uchar>(i)]++;

    // find max threshold value (pixels from [0-max_threshold] will be removed)
    int max_threshold = (int)histogram.size() - 1;
    for ( ; max_threshold >= 0 && n > 0; --max_threshold ) {
        n -= histogram[max_threshold];
    }

    if ( max_threshold < 0 )  // nothing to do
        src.copyTo(result);
    else     
        cv::threshold(src, result, max_threshold, 0., cv::THRESH_TOZERO);

    return result;
}

Usage example: get top 1%

auto top1 = filter_brightest( img, int((img.rows*img.cols) * .01) );
like image 32
Tom Avatar answered Oct 09 '22 10:10

Tom