首页 › 论坛 › AIDI-软件使用 › AIDI-软件使用【3.0系列】 › 【AIDI3.2】区域计算工具中使用opencv进行简单的图像处理
标签: 区域计算脚本
-
作者帖子
-
五月 17, 2024 1:05 下午 #292
aqrose
管理员- 需求场景:需要在区域计算工具通过简单的二值化检出缺陷区域;由于当前aidi图像库并不完善,因此需要通过调用opencv完成此功能
- 操作步骤:
- 第一步:进入aidi安装目录,命令行执行python -m pip install opencv-python,即可安装opencv
- 第二步:进入区域计算工具,编辑脚本,脚本内容如下(附件为python代码文件)
-
import math
import visionflow as vf
from visionflow import img
from visionflow import geometry as geo
from visionflow import param, props
import numpy as np
import cv2
from ctypes import *def region_calculate(sample: vf.ISample) -> props.PolygonRegionList:
ply_region_list = props.PolygonRegionList()
image = sample.get(vf.ToolNodeId(“输入”, “image”)).image().visual_image(0)
# 获取图像指针
pythonapi.PyCapsule_GetPointer.restype = c_void_p
pythonapi.PyCapsule_GetPointer.argtypes = [py_object, c_char_p]
ptr = pythonapi.PyCapsule_GetPointer(image.data(0), None)
# 传递给numpy
buffer = create_string_buffer(image.data_size(0))
memmove(buffer, ptr, image.data_size(0))
np_arr = np.frombuffer(buffer, dtype=np.uint8, count=image.data_size(0))
image_shape = (image.height(), image.width(), image.channels())
cv_mat = np_arr.reshape(image_shape)
# 转换为灰度图
gray = cv2.cvtColor(cv_mat, cv2.COLOR_BGR2GRAY)# 对灰度图进行二值化
_, binary = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY)
# cv2.imwrite(“D:/debug/test.png”, binary)# 查找轮廓
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)# contours转为PolygonRegion
for contour in contours:
ring_points = []
for point in contour:
geo_point = geo.Point2f(point[0][0], point[0][1])
ring_points.append(geo_point)
poly = geo.Polygon2f()
poly.outer = geo.return_correct(geo.Ring2f(ring_points))poly_region = vf.PolygonRegion()
poly_region.set_polygon(poly)
poly_region.set_name(“Default”)
ply_region_list.add(poly_region)
return ply_region_list
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
-
该话题由
aqrose 于 1年前 修正。
附件:
您需要登录才能查看附件。九月 5, 2024 9:26 下午 #338aqrose
管理员np_arr = np.ctypeslib.as_array(cast(ptr, POINTER(c_uint8 * image.data_size(0))).contents)
使用以上方式将aidi图像指针转换为numpy数组效率更高
-
作者帖子
- 哎呀,回复话题必需登录。