草庐IT

(P4)Python plt显示和保存图像(cv2、Image)

木槿qwer 2024-01-02 原文

Python plt显示图片

文章目录

概述

对这篇博客内容的最最简要的总结,便于快速抓要点

# 显示曲线
plt.plot(x,y)
# 显示图像
plt.imshow(image)
# 显示曲线/图片时需要的一行。本地可以显示,服务器不太行
plt.show() 
plt.savefig('xx.png') # 保存图片 fig.savefig('xx.png') 功能相同
# 保存图片在本地需要写明图片完整目录,服务器中默认保存在当前执行目录

一、绘制曲线并显示 plt.plot

参考资料:【Python】 【绘图】plt.figure()的使用

以下是一张图中包含多张小图 的三种不同写法的汇总和拆解。

汇总

plt.subplot(221)
plt.plot(x, y)

fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
ax1.plot(x, y)

fig = plt.figure(figsize=(6, 3)) # 指定画图的大小
ax = fig.add_subplot(1, 2, 1)
ax.plot(x, y)

写法一

plt.subplot(221)
plt.plot(x, x)
plt.show()  /  %matplotlib inline # %的写法只在Jupyter中生效,见文末附录说明
import numpy as np  
import matplotlib.pyplot as plt  
x = np.arange(1, 101)  
#作图1
plt.subplot(221)  
plt.plot(x, x)  
#作图2
plt.subplot(222)  
plt.plot(x, -x)  
 #作图3
plt.subplot(223)  
plt.plot(x, x ** 2)  
plt.grid(color='r', linestyle='--', linewidth=1, alpha=0.3)
#作图4
plt.subplot(224)  
plt.plot(x, np.log(x))  
plt.show()  # 删除本行,增加%matplotlib inline 也可以显示出图像 

写法二

fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
ax1.plot(x, x)
plt.show() 
import numpy as np  
import matplotlib.pyplot as plt

x = np.arange(1, 101)  
#划分子图
fig,axes=plt.subplots(2,2)
ax1=axes[0,0]
ax2=axes[0,1]
ax3=axes[1,0]
ax4=axes[1,1]


#作图1
ax1.plot(x, -x)  
#作图2
ax2.plot(x, x)
 #作图3
ax3.plot(x, x ** 2)
ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)
#作图4
ax4.plot(x, np.log(x))  
plt.show() 

写法三

fig = plt.figure(figsize=(6, 3)) # 指定画图的大小
ax = fig.add_subplot(1, 2, 1)
ax.plot(x, y)
plt.show() 
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline

fig = plt.figure(figsize=(6, 3))
ax = fig.add_subplot(1, 2, 1)
x = np.linspace(-5, 5, 100)
y = x**2
ax.plot(x, y, 'r-')

ax = fig.add_subplot(1, 2, 2)
x = np.linspace(-5, 5, 100)
y = x**3
ax.plot(x, y, 'r-')

plt.show() 

二、打开图片并显示 plt.imshow

已知的读取图片方式有两种:cv2、Image,初略讲解如下,有需要更多讲解的再单独整合。

写法一 cv2

参考资料
opencv 因为历史原因, 读入的图片的格式是BGRmatplotlib的图片格式默认是RGB格式的。所以,当用cv2读入图片然后用matplotlib显示的时候,R通道变成了B通道, B通道变成了R通道, 所以显示会很阴间。如果想要正确显示图像,就需要使用cvtColor进行颜色空间的转换,从BGR转换为RGB。

关键代码

image = cv2.imread(image_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
fig, ax = plt.subplots(1,2)
ax[0].imshow(image)
cv2.imwrite("1.jpg",image) # 保存图片

举例

import cv2
import matplotlib.pyplot as plt
image_path = r"C:\\Users\\shmily\\Desktop\\file1.jpg"
image = cv2.imread(image_path)
h, w, _ = image.shape
image_size = 448
img = cv2.resize(image, dsize=(image_size, image_size), interpolation=cv2.INTER_LINEAR)
h1, w1, _ = img.shape
print(h,w,h1,w1)

fig, ax = plt.subplots(1,2)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 	# 改变显示的颜色
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 
ax[0].imshow(image) # ,cmp='gray')
ax[1].imshow(img)
plt.show()

不进行 cv2.cvtColor 的结果

进行了颜色转变的结果

写法二 Image

关键代码

img = np.array(Image.open(img_path)) 
plt.figure()
plt.imshow(img)

举例

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
img_path = r"C:\\Users\\shmily\\Desktop\\file1.jpg"
img = np.array(Image.open(img_path)) 
plt.figure()
plt.imshow(img)
plt.show()

附录

1、%matplotlib inline 说明

2、随手补充内容

隐藏坐标系

plt.axis('off')

有关(P4)Python plt显示和保存图像(cv2、Image)的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby-on-rails - 使用 Sublime Text 3 突出显示 HTML 背景语法中的 ERB? - 2

    所以我在关注Railscast,我注意到在html.erb文件中,ruby代码有一个微弱的背景高亮效果,以区别于其他代码HTML文档。我知道Ryan使用TextMate。我正在使用SublimeText3。我怎样才能达到同样的效果?谢谢! 最佳答案 为SublimeText安装ERB包。假设您安装了SublimeText包管理器*,只需点击cmd+shift+P即可获得命令菜单,然后键入installpackage并选择PackageControl:InstallPackage获取包管理器菜单。在该菜单中,键入ERB并在看到包时选择

  4. ruby-on-rails - link_to 不显示任何 rails - 2

    我试图在索引页中创建一个超链接,但它没有显示,也没有给出任何错误。这是我的index.html.erb代码。ListingarticlesTitleTextssss我检查了我的路线,我认为它们也没有问题。PrefixVerbURIPatternController#Actionwelcome_indexGET/welcome/index(.:format)welcome#indexarticlesGET/articles(.:format)articles#indexPOST/articles(.:format)articles#createnew_articleGET/article

  5. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  6. ruby-on-rails - Ruby 检查日期时间是否为 iso8601 并保存 - 2

    我需要检查DateTime是否采用有效的ISO8601格式。喜欢:#iso8601?我检查了ruby​​是否有特定方法,但没有找到。目前我正在使用date.iso8601==date来检查这个。有什么好的方法吗?编辑解释我的环境,并改变问题的范围。因此,我的项目将使用jsapiFullCalendar,这就是我需要iso8601字符串格式的原因。我想知道更好或正确的方法是什么,以正确的格式将日期保存在数据库中,或者让ActiveRecord完成它们的工作并在我需要时间信息时对其进行操作。 最佳答案 我不太明白你的问题。我假设您想检查

  7. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  8. ruby-on-rails - 复数 for fields_for has_many 关联未显示在 View 中 - 2

    目前,Itembelongs_toCompany和has_manyItemVariants。我正在尝试使用嵌套的fields_for通过Item表单添加ItemVariant字段,但是使用:item_variants不显示该表单。只有当我使用单数时才会显示。我检查了我的关联,它们似乎是正确的,这可能与嵌套在公司下的项目有关,还是我遗漏了其他东西?提前致谢。注意:下面的代码片段中省略了不相关的代码。编辑:不知道这是否相关,但我正在使用CanCan进行身份验证。routes.rbresources:companiesdoresources:itemsenditem.rbclassItemi

  9. ruby-on-rails - 在 Flash 警报 Rails 3 中显示错误消息 - 2

    如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]

  10. ruby-on-rails - 在 Ruby (on Rails) 中使用 imgur API 获取图像 - 2

    我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path

随机推荐