我只想使用 python 从图像中裁剪出内部白色矩形。我用
findContours
尝试过,但由于边缘不清楚,因此没有显示任何更好的输出。这个怎么做。有谁能够帮助我。我是新来的。
import cv2
import numpy as np
# Load the image
image = cv2.imread("doc.jpg")
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply binary thresholding
_, thresholded = cv2.threshold(gray, 128, 255, cv2.THRESH_BINARY)
cv2.imshow("thresholded", thresholded)
# Find contours
contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Filter contours
rects = []
for contour in contours:
# Approximate the contour to a polygon
polygon = cv2.approxPolyDP(contour, 0.01 * cv2.arcLength(contour, True), True)
# Check if the polygon has 4 sides and the aspect ratio is close to 1
if len(polygon) == 4 and abs(1 - cv2.contourArea(polygon) / (cv2.boundingRect(polygon)[2] * cv2.boundingRect(polygon)[3])) < 0.1:
rects.append(polygon)
# Draw rectangles
for rect in rects:
cv2.drawContours(image, [rect], 0, (0, 255, 0), 2)
# Show the result
cv2.imshow("Rectangles", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
我尝试过这个但没有成功。
我只想使用以下命令从图像中裁剪内部白色矩形 蟒蛇。
可以通过使用鼠标事件绑定来解决该问题。
只需根据需要绘制一个矩形,然后按 Enter 键即可。
片段:
import cv2
import numpy as np
cropping = False
x_start, y_start, x_end, y_end = 0, 0, 0, 0
image = cv2.imread('driver_licence.jpg')
oriImage = image.copy()
def mouse_crop(event, x, y, flags, param):
# grab references to the global variables
global x_start, y_start, x_end, y_end, cropping
# if the left mouse button was DOWN, start RECORDING
# (x, y) coordinates and indicate that cropping is being
if event == cv2.EVENT_LBUTTONDOWN:
x_start, y_start, x_end, y_end = x, y, x, y
cropping = True
# Mouse is Moving
elif event == cv2.EVENT_MOUSEMOVE:
if cropping == True:
x_end, y_end = x, y
# if the left mouse button was released
elif event == cv2.EVENT_LBUTTONUP:
# record the ending (x, y) coordinates
x_end, y_end = x, y
cropping = False # cropping is finished
refPoint = [(x_start, y_start), (x_end, y_end)]
if len(refPoint) == 2: #when two points were found
roi = oriImage[refPoint[0][1]:refPoint[1][1], refPoint[0][0]:refPoint[1][0]]
cv2.imshow("Cropped", roi)
cv2.imwrite('crop.jpg', roi)
cv2.namedWindow("image")
cv2.setMouseCallback("image", mouse_crop)
while True:
i = image.copy()
if not cropping:
cv2.imshow("image", image)
elif cropping:
cv2.rectangle(i, (x_start, y_start), (x_end, y_end), (255, 0, 0), 2)
cv2.imshow("image", i)
cv2.waitKey(1)
cv2.destroyAllWindows()