How to speed up the loop when dealing with the numpy array of an image

Hi everyone,
I have an image that I want to estimate whether the background color is 'black' or 'white' at the border area (for example: 20% from the border). My current approach is to count all of those 'white' pixel and divided it to the total number of pixels.
Here is the code which I am using:

    def find_white_background_border( imgArr, threshold = 0.45):
        """Detect if backgournd of the image is white based on the pixels 20% from the border"""
        rate = 0.2
        background = np.array([255, 255, 255])
        
        y, x = len(imgArr), len(imgArr[0])
        diff_y, diff_x = int((y * rate)/2), int((x * rate)/2)

        count, white_count = 0,0
		# Can the following loops be improved ???
        for i_row in range(y):
            for i_col in range(x):
                if i_row > diff_y and i_row < y - diff_y and i_col > diff_x and i_col < x - diff_x:
                    continue
                count += 1

                if np.array_equal(imgArr[i_row][i_col], background):
                    white_count += 1

        percent = white_count/count
        # print("white percent = {}".format(percent))
        if percent >= threshold:
            return True, percent
        else:
            return False, percent

I could get the result which I wanted. However, I was hoping if anyone could help me to speed up the 2 for loops which I am using here.

Thank you for reading.
All of your suggtions are appreciated.

Comments (0)