更新** 尝试添加一些似乎有意义但仍然没有给我预期效果的代码。
您好,我对裁剪图像的全部内容很感兴趣,我可以使用 OpenCV 的矩形函数将其隔离。执行此操作后,我希望能够将裁剪后的内容应用到白色背景。
这是我的原图
我已经能够使用矩形隔离的图像如下:
目前我使用的代码如下:
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))
我添加的新代码导致此输出。
如上面的代码所示,我尝试将所有矩形的坐标添加到一个数组中,然后尝试迭代并将它们编译到单个图像中。从理论上讲,我认为这应该可行,但它没有给我想要的结果。任何帮助将不胜感激
谢谢!
最佳答案
简单来说:没有父级的轮廓是外轮廓。
回答this question可能会帮助您了解如何使用此“层次结构”。上面的代码是用C++写的,用Python应该也差不多。
关于python - OpenCV 裁剪矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21127638/