如何修复此堆栈溢出错误(python)?

2024-04-18 02:42:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算图像中一个补丁中相似颜色像素的数量。我正在尝试用openCV来实现它,并为此创建了一个函数。 后来我发现openCV中有一个函数可以用来做这件事,但我很好奇为什么它会显示这个错误。你知道吗

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

Tags: inpyimgforlinerangecv2file
1条回答
网友
1楼 · 发布于 2024-04-18 02:42:01
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))

下面给出了图像的输出

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

full imagepatch image

相关问题 更多 >