python opencv TypeError: Layout of the output array incompatible with cv::Mat

前端 未结 5 1097
温柔的废话
温柔的废话 2021-01-02 01:54

I\'m using the selective search here: http://koen.me/research/selectivesearch/ This gives possible regions of interest where an object might be. I want to do some processing

相关标签:
5条回答
  • 2021-01-02 02:11

    Just for the sake of completeness, it seems that many of us have used the solution of Etienne Perot above, minus .copy(). Converting the array type to int is enough. For example, when using the Hough transform:

        # Define the Hough transform parameters
        rho,theta,threshold,min,max = 1, np.pi/180, 30, 40, 60  
    
        image = ima.astype(np.uint8) # assuming that ima is an image.
    
        # Run Hough on edge detected image
        lines = cv2.HoughLinesP(sob, rho, theta, threshold, np.array([]), min, max)
    
        # Iterate over the output "lines" and draw lines on the blank 
        line_image = np.array([[0 for col in range(x)] for row in range(y)]).astype(np.uint8)
    
        for line in lines: # lines are series of (x,y) coordinates
            for x1,y1,x2,y2 in line:
                cv2.line(line_image, (x1,y1), (x2,y2), (255,0,0), 10)
    

    Only then could the data be plotted out using plt.imshow()

    0 讨论(0)
  • 2021-01-02 02:12

    My own solution was simply to ask a copy of original array...(god & gary bradski knows why...)

    im = dbimg[i]
    bb = boxes[i]  
    m = im.transpose((1, 2, 0)).astype(np.uint8).copy() 
    pt1 = (bb[0],bb[1])
    pt2 = (bb[0]+bb[2],bb[1]+bb[3])  
    cv2.rectangle(m,pt1,pt2,(0,255,0),2)  
    
    0 讨论(0)
  • 2021-01-02 02:20

    Another reason may be that the array is not contiguous. Making it contiguous would also solve the issue

    image = np.ascontiguousarray(image, dtype=np.uint8)

    0 讨论(0)
  • 2021-01-02 02:26

    Opencv appears to have issues drawing to numpy arrays that have the data type np.int64, which is the default data type returned by methods such as np.array and np.full:

    >>> canvas = np.full((256, 256, 3), 255)
    >>> canvas
    array([[255, 255, 255],
           [255, 255, 255],
           [255, 255, 255]])
    >>> canvas.dtype
    dtype('int64')
    >>> cv2.rectangle(canvas, (0, 0), (2, 2), (0, 0, 0))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Layout of the output array img is incompatible with cv::Mat (step[ndims-1] != elemsize or step[1] != elemsize*nchannels)
    

    The solution is to convert the array to np.int32 first:

    >>> cv2.rectangle(canvas.astype(np.int32), (0, 0), (2, 2), (0, 0, 0))
    array([[  0,   0,   0],
           [  0, 255,   0],
           [  0,   0,   0]], dtype=int32)
    
    0 讨论(0)
  • 2021-01-02 02:27

    The solution was to convert found first to a numpy array, and then to recovert it into a list:

    found = np.array(found)
    boxes = cv2.groupRectangles(found.tolist(), 1, 2)
    
    0 讨论(0)
提交回复
热议问题