python-3.x - 在图像中查找主线(及其角度)
问题描述
我想识别图像中的主线及其角度(穿过图像中心的线)。我从一个图像开始(参见链接,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()
解决方案
如评论中所述,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)
推荐阅读
- android - 无效的
对于 appcompat 和 Drawerlayout 源文件中的给定资源值 - c - 为什么 pthread 在 c 中的行为是这样的
- python - 在不更改 nan 值的情况下替换 pandas 上的值
- debugging - Amazon Linux2 EC2 上的 nodejs 日志上未显示颜色
- python - UnboundLocalError 只是当我尝试在我的类中定义一个变量时。如何在python中解决这个问题?
- maven - 将 Maven 的“versions:use-latest-versions”迁移到 Gradle
- javascript - 错误消息:./src/firebase.js 未找到模块:无法解析“firebase”
- python - df 中缺少日期
- python - 我有 2 个同时使用 cv2.videocapture 的 python 文件,每次都返回相机索引错误
- azure-data-factory - 在映射数据流中将字符串转换为日期、日期时间或 Int