OpenCV查找轮廓的中线[Python]

如何解决OpenCV查找轮廓的中线[Python]

在我的图像处理项目中,我已经使用cv.findContours函数获得了蒙版图像(黑白图像)及其轮廓。我现在的目标是创建一种算法,可以为此轮廓绘制一条中间线。掩盖的图像及其轮廓如下图所示。

屏蔽的图像:

Masked image

轮廓:

Contour

在我的想象中,对于该轮廓,我想创建一条接近水平的中线。我已经用红色手动标记了理想的中间线。请检查下图是否显示我提到的红色中间线。

轮廓与中线:

Contour with middle line

值得注意的是,我的最终目标是找到用黄色标记的尖端。如果您还有其他想法可以直接找到黄色的提示点,也请告诉我。为了找到黄色的尖点,我尝试了两种方法cv.convexHullcv.minAreaRect,但是问题是鲁棒性。我使这两种方法适用于某些图像,但对于我的数据集中的某些其他图像,它们的效果不是很好。因此,我认为找到中间线可能是一种可以尝试的好方法。

解决方法

我相信您正在尝试确定轮廓的重心和方向。我们可以使用Central Moments轻松地做到这一点。有关here的更多信息。

下面的代码生成this plot。这是您想要的结果吗?

# Determine contour
img = cv2.imread(img_file,cv2.IMREAD_GRAYSCALE)
img_bin = (img>128).astype(np.uint8)
contours,_ = cv2.findContours(img_bin,mode=cv2.RETR_EXTERNAL,method=cv2.CHAIN_APPROX_NONE)

# Determine center of gravity and orientation using Moments
M = cv2.moments(contours[0])
center = (int(M["m10"] / M["m00"]),int(M["m01"] / M["m00"]))
theta = 0.5*np.arctan2(2*M["mu11"],M["mu20"]-M["mu02"])
endx = 600 * np.cos(theta) + center[0] # linelength 600
endy = 600 * np.sin(theta) + center[1]

# Display results
plt.imshow(img_bin,cmap='gray')
plt.scatter(center[0],center[1],marker="X")
plt.plot([center[0],endx],[center[1],endy])
plt.show()
,

我现在的目标是创建一种算法,可以为此轮廓绘制一条中间线。

如果您检测到水平线的上下边界,则可以计算中线坐标。

例如:

enter image description here

中线将是:

enter image description here

如果将尺寸更改为图像的宽度:

enter image description here

代码:


import cv2

img = cv2.imread("contour.jpg")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
(h,w) = img.shape[:2]

x1_upper = h
x1_lower = 0
x2_upper = h
x2_lower = 0
y1_upper = h
y1_lower = 0
y2_upper = h
y2_lower = 0

lines = cv2.ximgproc.createFastLineDetector().detect(gray)

for cur in lines:
    x1 = cur[0][0]
    y1 = cur[0][1]
    x2 = cur[0][2]
    y2 = cur[0][3]

    # upper-bound coords
    if y1 < y1_upper and y2 < y2_upper:
        y1_upper = y1
        y2_upper = y2
        x1_upper = x1
        x2_upper = x2
    elif y1 > y1_lower and y2 > y2_lower:
        y1_lower = y1
        y2_lower = y2
        x1_lower = x1
        x2_lower = x2


print("\n\n-lower-bound-\n")
print("({},{}) - ({},{})".format(x1_lower,y1_lower,x2_lower,y2_lower))
print("\n\n-upper-bound-\n")
print("({},{})".format(x1_upper,y1_upper,x2_upper,y2_upper))

cv2.line(img,(x1_lower,y1_lower),(x2_lower,y2_lower),(0,255,0),5)
cv2.line(img,(x1_upper,y1_upper),(x2_upper,y2_upper),255),5)

x1_avg = int((x1_lower + x1_upper) / 2)
y1_avg = int((y1_lower + y1_upper) / 2)
x2_avg = int((x2_lower + x2_upper) / 2)
y2_avg = int((y2_lower + y2_upper) / 2)

cv2.line(img,y1_avg),(w,y2_avg),(255,5)

cv2.imshow("result",img)
cv2.waitKey(0)
cv2.destroyAllWindows()
,

这是通过Python / OpenCV计算围绕对象的旋转边界框的中心线的另一种方法。

输入:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread("blob_mask.jpg")

# convert to gray
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# threshold the grayscale image
thresh = cv2.threshold(gray,cv2.THRESH_BINARY)[1]

# get coordinates of all non-zero pixels
# NOTE: must transpose since numpy coords are y,x and opencv uses x,y
coords = np.column_stack(np.where(thresh.transpose() > 0))

# get rotated rectangle from 
rotrect = cv2.minAreaRect(coords)
box = cv2.boxPoints(rotrect)
box = np.int0(box)
print (box)

# get center line from box
# note points are clockwise from bottom right
x1 = (box[0][0] + box[3][0]) // 2
y1 = (box[0][1] + box[3][1]) // 2
x2 = (box[1][0] + box[2][0]) // 2
y2 = (box[1][1] + box[2][1]) // 2

# draw rotated rectangle on copy of img as result
result = img.copy()
cv2.drawContours(result,[box],2)
cv2.line(result,(x1,y1),(x2,y2),2)

# write result to disk
cv2.imwrite("blob_mask_rotrect.png",result)

# display results
cv2.imshow("THRESH",thresh)
cv2.imshow("RESULT",result)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res