如何保存带有线条、圆形标注的Python OpenCV处理图像?
解决方法
你调用的cv2.line、cv2.circle都是直接在corte_imagem数组对象上原地修改绘制标注的,直接用OpenCV自带的cv2.imwrite()方法就能把带标注的图像保存到本地。
注意事项
- OpenCV的图像默认是BGR通道顺序,如果你保存的结果颜色和预览时不一致,可以先做通道转换再保存
- 你现有代码里的
cv2.destoryAllWindows存在拼写错误,正确写法是cv2.destroyAllWindows
修改后的代码示例
d_ref = min(dh,dv) cor_linha = (255,0,0) esp_linha = 1 # 所有绘制操作都是原地修改corte_imagem l1 = cv2.line(corte_imagem,(int(dh/2+0.9*d_ref/2),int(dv/2-0.9*d_ref/2)),(int(dh/2-0.9*d_ref/2),int(dv/2+0.9*d_ref/2)),cor_linha,esp_linha) l2 = cv2.line(corte_imagem,(int(dh/2-0.9*d_ref/2),int(dv/2-0.9*d_ref/2)),(int(dh/2+0.9*d_ref/2),int(dv/2+0.9*d_ref/2)),cor_linha,esp_linha) cv2.circle(corte_imagem,(int(dh/2),int(dv/2)),int(0.9*d_ref/2),cor_linha,esp_linha) cv2.circle(corte_imagem,(int(dh/2),int(dv/2)),int(0.9*d_ref/3),cor_linha,esp_linha) cv2.circle(corte_imagem,(int(dh/2),int(dv/2)),int(0.9*d_ref/6),cor_linha,esp_linha) # 保存图像:如果要和显示的RGB效果一致,先转通道再保存 save_img = cv2.cvtColor(corte_imagem, cv2.COLOR_BGR2RGB) # 第一个参数是保存路径,第二个是图像数组,支持jpg、png等常见格式 cv2.imwrite('标注后的晶粒图像.png', save_img) cv2.imshow('imagem',save_img) cv2.waitKey(0) # 修正拼写错误 cv2.destroyAllWindows() cv2.waitKey(1)
其他可选方案
如果需要额外调整图像分辨率、添加自定义文字标注等需求,也可以用PIL库保存:
from PIL import Image # 转成PIL对象后保存 pil_img = Image.fromarray(save_img) pil_img.save('标注后的晶粒图像.png')
内容的提问来源于stack exchange,提问作者Leonardo Araujo
相关产品推荐
相关产品推荐

