首页 > 解决方案 > 在图像中查找主线(及其角度)

问题描述

我想识别图像中的主线及其角度(穿过图像中心的线)。我从一个图像开始(参见链接,https://i.stack.imgur.com/JfoHC.png)我已经使用 ImageJ 进行了预处理(减少噪声、阴影和查找边缘)。任何帮助将非常感激!

到目前为止我的代码,

import cv2 as cv
import numpy as np
import matplotlib as plt
import matplotlib.pyplot as pltt
from scipy.stats import linregress

# Import image and convert to grayscale
im = cv.imread(https://i.stack.imgur.com/JfoHC.png)
pltt.imshow(im)
pltt.show()
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)

# Convert grayscale image into binary mask
ret, thresh = cv.threshold(imgray, 200, 255, cv.THRESH_OTSU)

# Find contours in binary mask and plot binary mask
_, contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
window_name = 'Thresh'
pltt.imshow(thresh)
pltt.show()
cnt = contours[0]
M = cv.moments(thresh)
rows,cols = im.shape[:2]

# Fit line to identified contours in image and plot the results
[vx,vy,x,y] = cv.fitLine(cnt, cv.DIST_L2,0,0.01,0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
line = cv.line(im,(cols-1,righty),(0,lefty),(0,255,0),2)
window_name = 'Image'
color = (0, 255, 0)
thickness = 9
imagee = cv.line(im, (cols-1,righty),(0,lefty),(0,255,0),2)
cv.imshow(window_name, imagee)
pltt.imshow(imagee)
pltt.show()

使用 ImageJ 进行图像预处理和边缘检测的结果 使用 Python 3.7 (OpenCV) 的二进制阈值结果 我上面的代码的结果:符合轮廓的线

标签: python-3.xopencvcomputer-vision

解决方案


如评论中所述,cnt 0 可能不适合查看。

cv.drawContours(im, contours, 0, (0,250,0), 3)看到这一点很有用。

退房 - https://docs.opencv.org/3.4/d4/d73/tutorial_py_contours_begin.html

此外,如果您绘制“正确” - 最大轮廓,您仍然可能会得到一个奇怪的配合 - 但它不再远离事实:

MAX = 0 
for i in range(len(contours)):
    if len(contours[i]) > MAX:
        MAX = len(contours[i])
        MAX_ind = i

cv.drawContours(im, contours, MAX_ind, (100,255,0), 3)
pltt.imshow(im)

结果


推荐阅读