import cv2
import numpy as np
import time
def detect_a4_paper_and_shapes(frame):
start_time = time.time()
frame = cv2.resize(frame, (400, 300)) # 降低分辨率以提高性能
output_frame = frame.copy()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 50, 150)
contours, _ = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
a4_contour = None
for contour in contours:
if cv2.contourArea(contour) < 1000:
continue
peri = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * peri, True)
if len(approx) == 4:
if cv2.isContourConvex(approx):
a4_contour = approx
break
if a4_contour is not None:
cv2.drawContours(output_frame, [a4_contour], -1, (0, 0, 255), 2)
pts = a4_contour.reshape(4, 2)
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
maxWidth = max(int(widthA), int(widthB))
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32")
try:
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(frame, M, (maxWidth, maxHeight))
gray_warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray_warped, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
contours_warped, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours_warped:
area = cv2.contourArea(cnt)
if area < 100:
continue
peri = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.03 * peri, True)
shape = "未知"
if len(approx) == 3:
shape = "三角形"
elif len(approx) == 4:
x, y, w, h = cv2.boundingRect(approx)
aspect_ratio = float(w) / h
if 0.95 <= aspect_ratio <= 1.05:
shape = "正方形"
else:
shape = "长方形"
else:
perimeter = cv2.arcLength(cnt, True)
circularity = 4 * np.pi * area / (perimeter ** 2) if perimeter > 0 else 0
if 0.7 < circularity < 1.3:
shape = "圆形"
elif 5 <= len(approx) <= 8:
shape = "多边形"
M = cv2.moments(cnt)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
cv2.drawContours(warped, [cnt], -1, (0, 255, 0), 2)
cv2.putText(warped, shape, (cX - 30, cY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
h, w = warped.shape[:2]
if h < output_frame.shape[0] and w < output_frame.shape[1]:
output_frame[0:h, 0:w] = warped
else:
scale = min(output_frame.shape[0] / h, output_frame.shape[1] / w)
warped = cv2.resize(warped, (int(w * scale), int(h * scale)))
h, w = warped.shape[:2]
output_frame[0:h, 0:w] = warped
except Exception as e:
pass
fps = 1.0 / (time.time() - start_time)
cv2.putText(output_frame, f"FPS: {int(fps)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
return output_frame
def main():
cap = cv2.VideoCapture(0) # 使用树莓派的默认摄像头
if not cap.isOpened():
print("无法打开摄像头,请检查设备是否正常连接")
return
try:
while True:
ret, frame = cap.read()
if not ret:
print("无法获取视频帧,程序将退出")
break
processed_frame = detect_a4_paper_and_shapes(frame)
cv2.imshow("A4 Paper Shape Detection", processed_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
pass
finally:
cap.release()
cv2.destroyAllWindows()
if __name__ == "__main__":
main() 这个代码是不是有一个识别a4纸周边黑框的功能,能不能将识别到的黑框在界面中直接删除,然后识别a4中间的图形
最新发布