如何使用OpenCV/cv2在指定坐标检测恒星轮廓并绘制对应大小白点到新图

Name;RA(deg);Dec(deg);PixelX;PixelY;RPmag;Gmag;BPmag;Parallax;Flags ;313.311502;44.387289;2516;1458;4.850;4.728;4.681;5.8088;000800f0 ;313.327406;45.181692;236;2256;4.517;5.190;5.715;3.6700;000800f0 ;314.580976;44.472083;3131;4138;4.660;5.304;5.779;14.4950;00800f00 ;314.471585;44.788107;2143;4206;4.358;5.673;7.615;1.9323;000800f0 ...
基于OpenCV的实现方案
前置依赖安装
pip install opencv-python numpy pandas
核心实现代码
import cv2 import numpy as np import pandas as pd # 1. 加载星表数据,分号分隔 star_df = pd.read_csv("your_star_table.csv", sep=";") # 过滤坐标为空的无效行 star_df = star_df.dropna(subset=["PixelX", "PixelY"]) # 2. 加载观测图像 img = cv2.imread("kaEC6.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) h, w = gray.shape[:2] # 3. 新建黑色画布用于绘制匹配尺寸的白点 output = np.zeros_like(img) # 4. 逐个处理恒星坐标 roi_extend = 50 # 中心周围扩展的像素范围,根据恒星最大尺寸调整 threshold_offset = 20 # 二值化阈值偏移,亮于背景阈值offset的区域判定为恒星 for idx, row in star_df.iterrows(): cx = int(row["PixelX"]) cy = int(row["PixelY"]) # 过滤超出图像边界的无效坐标 if cx < 0 or cx >= w or cy <0 or cy >=h: continue # 截取中心周围的局部ROI,避免全图计算干扰和性能浪费 x1 = max(0, cx - roi_extend) y1 = max(0, cy - roi_extend) x2 = min(w, cx + roi_extend) y2 = min(h, cy + roi_extend) roi = gray[y1:y2, x1:x2] # 计算中心在ROI内的相对坐标 rel_cx = cx - x1 rel_cy = cy - y1 # 高斯模糊降噪后二值化,提取亮于背景的恒星区域 blk = cv2.GaussianBlur(roi, (5,5), 0) bg_mean = np.mean(blk) _, binary = cv2.threshold(blk, bg_mean + threshold_offset, 255, cv2.THRESH_BINARY) # 检测ROI内所有轮廓 contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 筛选包含当前恒星中心的目标轮廓 target_contour = None for cnt in contours: if cv2.pointPolygonTest(cnt, (rel_cx, rel_cy), False) >= 0: target_contour = cnt break if target_contour is None: # 未检测到轮廓时用默认最小半径,可按需调整 radius = 2 else: # 计算轮廓最小外接圆半径作为恒星尺寸 (_, _), radius = cv2.minEnclosingCircle(target_contour) radius = int(max(radius, 1)) # 在输出画布绘制对应尺寸的白色实心圆 cv2.circle(output, (cx, cy), radius, (255,255,255), -1) # 保存最终结果 cv2.imwrite("star_marked.jpg", output)
参数调整说明
roi_extend:如果图像中恒星尺寸较大,可增大该值保证截取到完整的恒星亮区threshold_offset:如果背景噪点被误识别为恒星,可增大该值提高阈值;如果暗星被漏识别,可减小该值- 若需要更精准的轮廓提取,可将普通阈值替换为
cv2.adaptiveThreshold做局部自适应阈值分割
内容的提问来源于stack exchange,提问作者kevin
相关产品推荐
相关产品推荐

