【问题标题】:Manipulating a large binary image array with numpy and cv2使用 numpy 和 cv2 操作大型二进制图像数组
【发布时间】:2014-07-28 17:34:05
【问题描述】:

我的代码如下:

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 显示可能(但非常慢)解决方案的行。你能给我推荐一个更好更快的解决方案吗?如果您这样做,我将不胜感激!

谢谢

【问题讨论】:

  • 也许它需要添加一个关于你想要达到的目标的句子
  • 正如我上面提到的,我想将二进制图像的黑点附加到self.bPoints,将白色点附加到形状为(2,2)的数组self.wPoints

标签: python arrays opencv numpy


【解决方案1】:

我假设 self.th2 是一个 numpy 数组。如果不是这种情况,这可能需要一些调整。基本上,这使用np.where 函数来确定0255 的所有索引。

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)

【讨论】:

  • 谢谢!快多了!但请注意,白色值是 255 而不是 1
  • 我在想np.where(),但我不知道如何操作它!这无疑是一种制作索引的好方法!
猜你喜欢
  • 2020-05-18
  • 1970-01-01
  • 2017-07-27
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 2015-10-16
  • 1970-01-01
  • 2018-06-30
相关资源
最近更新 更多