OpenCV裁剪矩形

时间:2014-01-15 01:44:08

标签: python opencv

UPDATE **尝试添加一些似乎有意义的代码,但仍然没有给我预期的效果。

您好我有兴趣裁剪 ALL OF 我使用OpenCV矩形函数隔离的图像内容。一旦我这样做,我希望能够将裁剪的内容应用到白色背景。

这是我原来的图片

2

我能够使用矩形隔离的图像如下:

1

我目前使用的代码如下:

import numpy as np
import cv2

im = cv2.imread('1.jpg')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)




contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

squares = []

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)

        if  h>28 and h<35:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            cv2.imwrite('norm1.jpg',im)
crop_img = [[[255, 255, 255] for x in xrange(377)] for x in xrange(377) ] #newly added code starts here
for s in squares:
     s = squares[0]
     x = s[0]
     y = s[1]
     w = s[2]
     h = s[3]
     img = im[y:y+h,x:x+w]
          for col in range(y,y+h):
              for row in range(x,x+w):
                  if img[col - y][row - x].tolist() == [0,0,0]:
                      crop_img[col][row] = [0,0,0]


cv2.imwrite("cropped.jpg", np.array(crop_img))

我添加的新代码会导致此输出。

3

如上面的代码所示,我尝试将所有矩形的坐标添加到数组中,然后尝试迭代并将它们编译到单个图像上。从理论上讲,我认为这应该有效,但它没有给我预期的结果。任何帮助将不胜感激

谢谢!

1 个答案:

答案 0 :(得分:0)

简单来说:没有父母的轮廓是外轮廓。

this question的回答可以帮助您理解如何使用这种“等级”。代码存在于C ++中,但在Python中应该类似。