用numpy和cv2操作大型二值图像阵列

2024-10-01 09:31:53 发布

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

我的代码如下:

import cv2; import numpy as np

class MyClass:
    def __init__(self,imagefile):
        self.image = cv2.imread(imagefile)

        #image details
        self.h,self.w = self.image.shape[:2]
        #self.bPoints, self.wPoints = np.array([[0,0]]),np.array([[0,0]])
        self.bPoints, self.wPoints = [],[]

        #CAUTION! Points are of the form (y,x)
        # Point filtering
        for i in xrange(self.h):
            for j in xrange(self.w):
                if self.th2.item(i,j) == 0:
                    #self.bPoints = np.append([[i,j]], self.bPoints, axis=0)
                    self.bPoints.append((i,j))
                else:
                    self.wPoints.append((i,j))
                    #self.wPoints = np.append([[i,j]], self.wPoints, axis=0)

        #self.bPoints = self.bPoints[:len(self.bPoints) - 1]
        #self.wPoints = self.wPoints[:len(self.wPoints) - 1]
        self.bPoints, self.wPoints = np.array(self.bPoints), np.array(self.wPoints)

我想找出并区分白点和黑点。我已经评论了通过numpy显示一个可能(但非常慢)解决方案的行。你能给我推荐一个更好更快的解决方案吗?如果你这么做,我会很感激的!在

谢谢


Tags: inimageimportselfnumpyfornparray
1条回答
网友
1楼 · 发布于 2024-10-01 09:31:53

我假设self.th2是一个numpy数组。如果不是这样的话,这可能需要一些调整。基本上,这使用np.where函数来确定0或{}的所有指标。在

import cv2; import numpy as np

class MyClass:
    def __init__(self,imagefile):
        self.image = cv2.imread(imagefile)

        #image details
        self.h,self.w = self.image.shape[:2]
        #self.bPoints, self.wPoints = np.array([[0,0]]),np.array([[0,0]])
        self.bPoints, self.wPoints = [],[]

        #CAUTION! Points are of the form (y,x)
        # use the np.where method instead of a double loop. 
        # make sure self.th2 is a numpy array
        indx = np.where(self.th2==0)
        for i,j in zip(indx[0], indx[1]):
            self.bPoints.append((i,j))

        indx = np.where(self.th2==255)
        for i,j in zip(indx[0], indx[1]):
            self.wPoints.append((i,j))

        # Point filtering
        #for i in xrange(self.h):
        #    for j in xrange(self.w):
        #        if self.th2.item(i,j) == 0:
        #            #self.bPoints = np.append([[i,j]], self.bPoints, axis=0)
        #            self.bPoints.append((i,j))
        #        else:
        #            self.wPoints.append((i,j))
        #            #self.wPoints = np.append([[i,j]], self.wPoints, axis=0)

        #self.bPoints = self.bPoints[:len(self.bPoints) - 1]
        #self.wPoints = self.wPoints[:len(self.wPoints) - 1]
        self.bPoints, self.wPoints = np.array(self.bPoints), np.array(self.wPoints)

相关问题 更多 >