Akshat
Akshat

Reputation: 3

How do I fix this stack overflow error (python)?

I am trying to count the number of similar colored pixels in a patch in an image. I am trying to do it with openCV and created a function to do so. I later figured there was a function available in openCV for doing it but I am curious why it is showing this error.

import cv2
img = cv2.imread('drops.jpg')

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

gray = cv2.resize(gray, (256, 256))


for i in range (256):
    for j in range(256):
        gray[i,j] = gray[i,j]//10


def flood(img, i, j, color):
    m = len(img[0])
    n = len(img)

    if (i<0 or i>=m or j<0 or j>=n):
        return 0

    if (img[i,j]!=color):
        return 0

    if (img[i,j]==255): #Error here
        return 0

    img[i,j] = 255

    return (1+flood(img, i+1, j, color) #Error here
    +flood(img, i, j+1, color)
    +flood(img, i-1, j, color)
    +flood(img, i, j-1, color)
    +flood(img, i-1, j-1, color)
    +flood(img, i+1, j-1, color)
    +flood(img, i-1, j+1, color)
    +flood(img, i+1, j+1, color))

def count(img):
    for i in range(256):
        for j in range(256):
            if(img[i,j]!=255):
                print(flood(img,i,j,img[i,j]))

count(gray)

Error:
Fatal Python error: Cannot recover from stack overflow.

Current thread 0x00005294 (most recent call first):
  File "E:\Coding\CBIR\images\CCV.py", line 24 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood
  File "E:\Coding\CBIR\images\CCV.py", line 36 in flood

Upvotes: 0

Views: 170

Answers (1)

Rinshan Kolayil
Rinshan Kolayil

Reputation: 1139

import cv2 as cv
from collections import Counter
from pathlib import Path
import os
from matplotlib import pyplot as plt
from sklearn.feature_extraction import image
from collections import Counter
p = Path("/content/gdrive/My Drive/Colab Notebooks/images/cats")
new_p = os.path.join(p,'cat.1.jpg')
im = cv.imread(new_p,cv.COLOR_RGB2BGR)
im = cv.resize(im,(150,150))
patches = image.extract_patches_2d(im, (50,50)) #you can add your own patches
new_list = patches[5].reshape(-1,3).tolist()
res = [str(i) for i in new_list]
print(Counter(res))

The output of images given below

plt.imshow(im)
plt.imshow(patches[5])

full image patch image

Upvotes: 1

Related Questions