Python 3.x 如何裁剪矩形或正方形内的图像区域?
首先我拍了这张照片,然后在上面画了一个矩形。现在我只想裁剪矩形内的图像。我试着画轮廓,但在我的情况下没有成功。我被卡住了。Python 3.x 如何裁剪矩形或正方形内的图像区域?,python-3.x,opencv,image-processing,crop,rectangles,Python 3.x,Opencv,Image Processing,Crop,Rectangles,首先我拍了这张照片,然后在上面画了一个矩形。现在我只想裁剪矩形内的图像。我试着画轮廓,但在我的情况下没有成功。我被卡住了。 import cv2 import numpy as np img = cv2.imread("C:/Users/hp/Desktop/segmentation/abc.jpg", 0); h, w = img.shape[:2] kernel = np.ones((15,15),np.uint8) e = cv2.erode(img,kernel,iterations
import cv2
import numpy as np
img = cv2.imread("C:/Users/hp/Desktop/segmentation/abc.jpg", 0);
h, w = img.shape[:2]
kernel = np.ones((15,15),np.uint8)
e = cv2.erode(img,kernel,iterations = 2)
d = cv2.dilate(e,kernel,iterations = 1)
ret, th = cv2.threshold(d, 150, 255, cv2.THRESH_BINARY_INV)
mask = np.zeros((h+2, w+2), np.uint8)
# cv2.floodFill(th, mask, (200,200), 255); # position = (200,200)
out = cv2.bitwise_not(th)
out= cv2.dilate(out,kernel,iterations = 3)
cnt, h = cv2.findContours(out,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(cnt)):
area = cv2.contourArea(cnt[i])
if(area>100):
mask = np.zeros_like(img)
cv2.drawContours(mask, cnt, i, 255, -1)
x,y,w,h = cv2.boundingRect(cnt[i])
crop= img[ y:h+y,x:w+x]
cv2.imshow("snip",crop )
if(cv2.waitKey(0))==27:break
cv2.destroyAllWindows()
考虑到矩形是黑色的,并且没有其他大的黑色元素连接在一起,这里是裁剪矩形内部的代码:
import cv2
import numpy as np
img = cv2.imread("abc.jpg", 0);
h, w = img.shape[:2]
# print(img.shape)
kernel = np.ones((3,3),np.uint8)
img2 = img.copy()
img2[img2!=0]=255
img2 = 255 - img2
img2 = cv2.dilate(img2, kernel)
img2 = cv2.medianBlur(img2, 9)
img2 = cv2.medianBlur(img2, 9)
position = np.where(img2 !=0)
x0 = position[0].min()
x1 = position[0].max()
y0 = position[1].min()
y1 = position[1].max()
print(x0,x1,y0,y1)
result = img[x0:x1,y0:y1]
result = cv2.resize(result,(800,800))
# rect = cv2.resize(np.hstack((img,img2)),(1000,700))
cv2.imshow('anything', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
导入cv2
将numpy作为np导入
img=cv2.imread('WwsqC.jpg');
h、 w=图像形状[:2]
thresh=7
im_gray=cv2.CVT颜色(img,cv2.COLOR_BGR2GRAY)
x_项目=np.中值(im_灰色,轴=0)
y_项目=np.中值(im_灰色,轴=1)
行=np.其中(x_项目
import cv2
import numpy as np
img = cv2.imread('WwsqC.jpg');
h, w = img.shape[:2]
thresh=7
im_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
x_proj=np.median(im_gray, axis=0)
y_proj=np.median(im_gray, axis=1)
rows = np.where(x_proj<thresh)[0]
cols = np.where(y_proj<thresh)[0]
crop=img[cols[0]:cols[-1], rows[0]:rows[-1] ]
cv2.imwrite('WwsqC.png', crop)