import cv2 import numpy as np import matplotlib.pyplot as plt

def solve(img): rows, cols, _ = img.shape img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_gas = cv2.GaussianBlur(img_gray, (7, 7), 0) img_threshold = cv2.threshold(img_gas, 0, 255, cv2.THRESH_OTSU+cv2.THRESH_BINARY_INV)[1]

# Calculate vertical projection
vert_proj = np.sum(img_threshold, axis=0)
vert_proj = vert_proj / np.max(vert_proj) * rows  # Normalize projection values to image height

# Plot vertical projection
fig, ax = plt.subplots()
ax.plot(vert_proj, range(cols))
ax.invert_yaxis()
ax.set_xlabel('Projection')
ax.set_ylabel('Column')
plt.show()

contours, _ = cv2.findContours(img_threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=lambda x: cv2.contourArea(x), reverse=True)

for cnt in contours:
    (x, y, w, h) = cv2.boundingRect(cnt)
    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 1)
    cv2.line(img, (x + int(w / 2), 0), (x + int(w / 2), rows), (0, 255, 0), 1)
    cv2.line(img, (0, y + int(h / 2)), (cols, y + int(h / 2)), (0, 255, 0), 1)
    break

cv2.imshow('huidu', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Python OpenCV 二值化图像垂直积分投影折线图实现

原文地址: https://www.cveoy.top/t/topic/nuKT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录