Edgar H
Edgar H

Reputation: 1518

Mask Image region for Otsu Threshold with OpenCV

I have images were certain regions are set to 255 to not interfere with the region of interest. When doing an Otsu threshold, these regions offset the threshold value.

Image with whited-out areas that throw off the Otsu threshold

I found a good answer how to do this but my python implementation is slow. Given that I rountinly run my script on 10'000 images, more speed would save me days.

Here an example of what I'm doing

        from __future__ import absolute_import, division, print_function
        #import matplotlib.pyplot as plt
        import numpy as np
        import cv2

        #Using the image provided in the question
        img = cv2.imread('imgSubbed-15.jpg', 0)

        yImg,xImg = img.shape
        how_many_255 = len(np.where(img==255)[0])
        tempThresImg = np.zeros((1,yImg * xImg - how_many_255), np.uint8)

        count=0
        for ii in range(xImg):
            for jj in range(yImg):
                if img[jj, ii] != 255:
                   tempThresImg[0, count] =  img[jj, ii]
                   count +=1

        threshold, temp = cv2.threshold(tempThresImg,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #using otsu threshold
        ret,thresh = cv2.threshold(img,threshold,255,cv2.THRESH_BINARY)

        threshold1, thresh1 = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) #using otsu threshold

        cv2.imshow('Standard Way', thresh1)
        cv2.imshow('Removed 255s', thresh)
        print('\n\nThreshold with Removal= %d \t Standard Threshold = %d \n\n' %(threshold, threshold1))

The thresholds are 226 versus 250.

Could anyone recommend a way to speed this up?

Upvotes: 1

Views: 5031

Answers (1)

Edgar H
Edgar H

Reputation: 1518

After following the answer Miki linked, I realized that one can index with conditions in Python. The explicit loop takes a second, the indexing is miliseconds.

     tempThresImg = img[img !=  255]

Upvotes: 1

Related Questions