在图像中添加标注并使用plt savefig函数保存

有时候需要读取图片,并添加标注,然后保存该图片。

如果用opencv 的imwrite函数不可行,因为imwrite函数需要输入参数是numpy数组。

此时用plt savefig函数可以保存该图片,但是savefig函数前面不能出现plt.show()函数。

代码案例:

import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
import cv2
 

lena = cv2.imread('/home/data/test.png',2)
print(lena.shape,lena.dtype)
plt.imshow(lena,'gray')
plt.show()

img = lena
h, w = img.shape[:2]
pixelSequence = img.reshape([h * w, ])
numberBins = 256
histogram, bins, patch = plt.hist(pixelSequence, numberBins,
                                  facecolor='black', histtype='bar')
plt.xlabel("gray label")
plt.ylabel("number of pixels")
plt.axis([0, 255, 0, np.max(histogram)])
plt.show()
lena.shape #(512, 512, 3)
circle = []
#print(lena.min(),lena.max(),lena[:][500])

f1 = img
#print(f1.max(),f1.min())
thresh_points = 10 ##标记的点数目上限
thresh_rad = 50 ##标记的点之间距离阈值
def label_ij(f1,thresh_points,thresh_rad,circle):
    for i in range(f1.shape[0]):
        for j in range(f1.shape[1]):
                if f1[i][j] == 255:
    
                    if len(circle)!= 0 and len(circle)<thresh_points:
                        for k in range(len(circle)):
                            if (circle[k][0]-i)**2 + (circle[k][1]-j)**2<thresh_rad:  ###当前坐标与已标记的坐标距离小于阈值则抛弃
                                break
                            elif k == len(circle)-1:  ###前面所有标记点距离该点都大于阈值,k表示轮流比较到了前面所有标记点的最后一个点
                                circle.append([i,j])
                    elif len(circle)==0:
                        circle.append([i,j])
                    else:
                        return circle
                else:
                    pass
circle = label_ij(f1,thresh_points,thresh_rad,circle)
print(len(circle))
plt.figure()
#plt.plot(circle[:][0], circle[:][1], 'g*-')
for i in range(len(circle)):
         plt.scatter(circle[i][0], circle[i][1],c='green',edgecolor='none',s=10)

 

plt.imshow(img,'gray') # 显示图片函数原型: 省略第二个参数,默认绘制彩图

plt.axis('on')
#plt.show()


#cv2.imwrite('/home/zhongjia/plasmabubble/data/test2.png',img)
plt.savefig('/home/zhongjia/plasmabubble/data/test2.png', dpi = 100)
#print(lena.shape,type(lena))

打开保存的结果图片:

当出现plt.shaow()函数时:

import matplotlib.pyplot as plt # plt 用于显示图片
import matplotlib.image as mpimg # mpimg 用于读取图片
import numpy as np
import cv2
 

lena = cv2.imread('/home/data/test.png',2)
print(lena.shape,lena.dtype)
plt.imshow(lena,'gray')
plt.show()

img = lena
h, w = img.shape[:2]
pixelSequence = img.reshape([h * w, ])
numberBins = 256
histogram, bins, patch = plt.hist(pixelSequence, numberBins,
                                  facecolor='black', histtype='bar')
plt.xlabel("gray label")
plt.ylabel("number of pixels")
plt.axis([0, 255, 0, np.max(histogram)])
plt.show()
lena.shape #(512, 512, 3)
circle = []
#print(lena.min(),lena.max(),lena[:][500])

f1 = img
#print(f1.max(),f1.min())
thresh_points = 10 ##标记的点数目上限
thresh_rad = 50 ##标记的点之间距离阈值
def label_ij(f1,thresh_points,thresh_rad,circle):
    for i in range(f1.shape[0]):
        for j in range(f1.shape[1]):
                if f1[i][j] == 255:
    
                    if len(circle)!= 0 and len(circle)<thresh_points:
                        for k in range(len(circle)):
                            if (circle[k][0]-i)**2 + (circle[k][1]-j)**2<thresh_rad:  ###当前坐标与已标记的坐标距离小于阈值则抛弃
                                break
                            elif k == len(circle)-1:  ###前面所有标记点距离该点都大于阈值,k表示轮流比较到了前面所有标记点的最后一个点
                                circle.append([i,j])
                    elif len(circle)==0:
                        circle.append([i,j])
                    else:
                        return circle
                else:
                    pass
circle = label_ij(f1,thresh_points,thresh_rad,circle)
print(len(circle))
plt.figure()
#plt.plot(circle[:][0], circle[:][1], 'g*-')
for i in range(len(circle)):
         plt.scatter(circle[i][0], circle[i][1],c='green',edgecolor='none',s=10)

 

plt.imshow(img,'gray') # 显示图片函数原型: 省略第二个参数,默认绘制彩图

plt.axis('on')
plt.show()


#cv2.imwrite('/home/zhongjia/plasmabubble/data/test2.png',img)
plt.savefig('/home/zhongjia/plasmabubble/data/test2.png', dpi = 100)
#print(lena.shape,type(lena))

打开保存的结果图片:

 可见保存图片是一片空白,plt.show()函数证明前面图像内容结束,后续代码已经与前面图像无关,此时保存图片内容为空。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值