2
更新**尝试添加一些代码似乎有道理,但仍然没有给我想要的效果。OpenCV裁剪矩形
你好,我有兴趣修剪ALL OF图像的内容我能够使用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))
我添加的新代码导致此输出。
如在代码看出上述我尝试添加所有矩形的坐标到一个数组,然后试图进行迭代和编译它们到单个的图像。理论上我认为这应该起作用,但它没有给我想要的结果。任何帮助将不胜感激
谢谢!