python︱matplotlib使用(读入、显示、写出、opencv混用、格式转换...)_<matplotlib.image.axesimage object at 0x7f1d27d0c2-程序员宅基地

技术标签: 图像opencv及图像基础技术  python  matplot  Python︱基础与数据处理  numpy  opencv  

opencv和matplotlib是比较常用的图像分析模块。在Ipython里面,opencv不能直接显示出来,所以有些时候会借助matplotlib来显示。

%matplotlib inline 

.
1、matplotlib的读入与显示

import matplotlib.pyplot as plt  
import numpy as np  
from PIL import Image  
  
img = Image.open('lena.png') # 读取的图像显示的<matplotlib.image.AxesImage object at 0x7f9f0c60f7f0>  
img.show()  
img.format  
  
region = img.transpose(Image.ROTATE_180) #翻转  
out = img.resize((128, 128)) # 改变大小  
out1 = img.rotate(45) #旋转  
plt.imshow(img) # 显示  
  
mean=np.array([104., 117., 124.]) #均值  
np.shape(img)  
img1 -= mean  
plt.imshow(img1)  

Image.open之后,是以<matplotlib.image.AxesImage object格式保存。
.
2、Image.open格式<—>矩阵

image.open转矩阵

img = Image.open('lena.png')
img1 = np.array(img)  

矩阵转 image.open

img = Image.open('lena.png')
img1 = np.array(img)  
Image.fromarray(img1 ) 

3、字节bytes<—>image.open格式以及矩阵格式

有的图片读入方式以.read(),读入之后为Bytes类型。

def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

这是要转换为图像格式以及array格式该怎么操作(BytesIO字节读入函数):

	# 转image.open格式——常规
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import numpy as np
Image.open(BytesIO(get_file_content(pic_path)))
	# 转成array格式——常规
np.array(Image.open(BytesIO(get_file_content(pic_path))))

BytesIO返回的格式为:<_io.BytesIO at 0x137c4f6f68>

3.1 从url读入并保存

一般情况下请求url的图像内容,使用的是:

from skimage import io
io.imread(url)

但是因为反扒策略,会出现报错:

RemoteDisconnected: Remote end closed connection without response

那么可以就可以使用:

import urllib.request
headers = {'User-Agent': 'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
req = request.Request(img_l, headers=headers)
pic_infos = request.urlopen(req).read()  # bytes格式读入

# 两种保存
misc.imsave(savepath, np.array(Image.open(BytesIO(pic_infos)))  )
Image.open(BytesIO(pic_infos)).save(savepath)

4 base64编码

图片路径 -> base64编码

def get_file_content_base64(filePath):
    #with open(filePath, 'rb') as fp:
    #    return fp.read()
    with open(filePath,"rb") as f:
    # b64encode是编码,b64decode是解码
        base64_data = base64.b64encode(f.read())
        return base64_data.decode('utf-8')

图片解码-> 显示

Image.open(BytesIO(base64.b64decode(body_result['image'])))

.
5、PIL格式保存

img = Image.open('lena.png')
img .save(savepath)

.
6、在ipython中显示图片

im=Image.open('/home/Picture/test.jpg')
im.show()

有些时候,show()出来,还没有出来,这时候需要加上:

%matplotlib inline

.

7、图像裁剪、旋转、改变

im=Image.open('/home/Picture/test.jpg')
box=(100,100,500,500)
# box=(x,y,x+w,y+h)
region=im.crop(box) #此时,region是一个新的图像对象。
img = Image.open('lena.png') # 读取的图像显示的
region = img.transpose(Image.ROTATE_180) #翻转  
out = img.resize((128, 128)) # 改变大小  
out1 = img.rotate(45) #旋转  
plt.imshow(img) # 显示  

.
8、opencv打开的图像用plt显示与保存

显示可以直接imshow

import matplotlib.pyplot as plt
import cv2
img = cv2.imread('01.jpg',cv2.IMREAD_COLOR)

%matplotlib inline
plt.subplot(111)
plt.imshow(img)

常规plt的保存方式为:

plt.savefig("test.png")

但是该方式,保存下来的结果带坐标系的内容,所以仅供观赏。

除了用cv2.imwrite保存cv2读的内容,保存可以用misc (不太对)

cv2.imwrite('img.jpg',img, [int(cv2.IMWRITE_JPEG_QUALITY), 100] )
from scipy import misc
# numpy直接保存出来
misc.imsave('img.jpg', img)

当然会出现通道错误,比如(左图是misc保存的,右图是cv2.imwrite保存的):
这里写图片描述


延伸一:更精致的画框(带中文)

code起初来源于项目:allanzelener/YAD2K
主要有两个函数:get_colors_for_classes(num_classes)
draw_boxes(image, boxes, box_classes, class_names, scores=None,fnt ="msyh.ttc" )

其中:get_colors_for_classes(num_classes),输入个数,就会返回相应的颜色,RGB值:

get_colors_for_classes(2)
>>> [(0, 255, 255), (255, 0, 0)]

那么draw_boxes函数各个参数的意思为:

  • image:矩阵(width, height, 3)
  • boxes:np.array,(y_min, x_min, y_max, x_max),比如:array([[120, 516, 221, 714], [306, 753, 363, 847], [148, 14, 222, 78]])
  • box_classes = [1,2,6],这里是下面的class_names索引,代表本次标注的内容;
  • class_names:[‘a’,‘b’,‘c’,‘d’,‘e’,‘f’],这里的class_names指的是全部的标签名称,不代表本次,代表全部;
  • scores=None:或者为np.array(['0.1','0.2','0.3'])
  • fnt =“msyh.ttc” ,这个为字体,一般要中文输入的话,需要指定中文的字体。
import colorsys
import random

import numpy as np
from PIL import Image, ImageDraw, ImageFont


def get_colors_for_classes(num_classes):
    """Return list of random colors for number of classes given."""
    # Use previously generated colors if num_classes is the same.
    if (hasattr(get_colors_for_classes, "colors") and
            len(get_colors_for_classes.colors) == num_classes):
        return get_colors_for_classes.colors

    hsv_tuples = [(x / num_classes, 1., 1.) for x in range(num_classes)]
    colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
    colors = list(
        map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
            colors))
    random.seed(10101)  # Fixed seed for consistent colors across runs.
    random.shuffle(colors)  # Shuffle colors to decorrelate adjacent classes.
    random.seed(None)  # Reset seed to default.
    get_colors_for_classes.colors = colors  # Save colors for future calls.
    return colors


def draw_boxes(image, boxes, box_classes, class_names, scores=None,fnt ="msyh.ttc" ):
    """Draw bounding boxes on image.
    Draw bounding boxes with class name and optional box score on image.
    Args:
        image: An `array` of shape (width, height, 3) with values in [0, 1].
        boxes: An `array` of shape (num_boxes, 4) containing box corners as
            (y_min, x_min, y_max, x_max).
        box_classes: A `list` of indicies into `class_names`.
        class_names: A `list` of `string` class names.
        `scores`: A `list` of scores for each box.
    Returns:
        A copy of `image` modified with given bounding boxes.
    """
    #image = Image.fromarray(np.floor(image * 255 + 0.5).astype('uint8'))
	image = Image.fromarray(image)
	
    font = ImageFont.truetype(
        font=fnt,
        size=np.floor(3e-2 * image.size[1] + 0.5).astype('int32'))
    thickness = (image.size[0] + image.size[1]) // 300

    colors = get_colors_for_classes(len(class_names))

    for i, c in list(enumerate(box_classes)):
        box_class = class_names[c]
        box = boxes[i]
        if isinstance(scores, np.ndarray):
            score = scores[i]
            label = '{} {:.2f}'.format(box_class, score)
        else:
            label = '{}'.format(box_class)

        draw = ImageDraw.Draw(image)
        label_size = draw.textsize(label, font)

        top, left, bottom, right = box
        top = max(0, np.floor(top + 0.5).astype('int32'))
        left = max(0, np.floor(left + 0.5).astype('int32'))
        bottom = min(image.size[1], np.floor(bottom + 0.5).astype('int32'))
        right = min(image.size[0], np.floor(right + 0.5).astype('int32'))
        print(label, (left, top), (right, bottom))

        if top - label_size[1] >= 0:
            text_origin = np.array([left, top - label_size[1]])
        else:
            text_origin = np.array([left, top + 1])

        # My kingdom for a good redistributable image drawing library.
        for i in range(thickness):
            draw.rectangle(
                [left + i, top + i, right - i, bottom - i], outline=colors[c])
        draw.rectangle(
            [tuple(text_origin), tuple(text_origin + label_size)],
            fill=colors[c])
        draw.text(text_origin, label, fill=(0, 0, 0), font=font)
        del draw

    return np.array(image)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/sinat_26917383/article/details/78559709

智能推荐

linux centos7安装redis_linux7安装redis客户端-程序员宅基地

文章浏览阅读312次。linux安装redis_linux7安装redis客户端

动态规划入门感悟_动态规划的基本思想及感悟-程序员宅基地

文章浏览阅读357次,点赞2次,收藏3次。不会动态规划的可以看看我博客里动态规划入门一文哦http://blog.csdn.net/qq_39670434/article/details/77414362在这里为了帮助萌新们学习动态规划,调用几篇大佬的好文章http://blog.csdn.net/baidu_28312631/article/details/47418773http://blog.csdn.net_动态规划的基本思想及感悟

单片机上电不断重启复位_stc8f单片机勾选低压复位单片机不断复位怎么解决-程序员宅基地

文章浏览阅读7.7k次,点赞4次,收藏15次。单片机不断重启复位的原因主要是一个原因;就是单片机在不断复位造成复位的原因有几个;1、单片机硬件复位,这个要检查硬件电路中的复位电路是不是有错误2、单片机程序中有代码造成软件复位3、单片机在不断上电断电循环过程造成不断复位主要讲一下第三种情况,这种情况的主要原因的因为外部电源供电不足导致单片机不断复位。你先检查一下自己的电路中是否有很多需要供电的模块,比如电机,制冷发热类的模块等等需要..._stc8f单片机勾选低压复位单片机不断复位怎么解决

哈尔滨工业大学计算机科学与技术学院许博文,王轩-哈尔滨工业大学(深圳)计算机科学与技术学院...-程序员宅基地

文章浏览阅读573次。一、近三年发表期刊论文[1]第一作者及通讯作者论文1)Yulin Wu, Xuan Wang, Zoe L. Jiang, etc. Efficient Server-Aided Secure Two-Party Computation in Heterogeneous Mobile Cloud Computing, IEEE Transactions on Dependable and Secu..._ansactions on dependable and secure computing

Prometheus源码学习(8) scrape总体流程_promethus scrapes-程序员宅基地

文章浏览阅读1.2k次。1. main 函数中初始化 scrapeManager 实例// 初始化 scrapeManager,fanout Storage 是一个读写多个底层存储的代理scrapeManager = scrape.NewManager(log.With(logger, "component", "scrape manager"), fanoutStorage)fanoutStorage 是读写多个底层存储的代理,实现了 storage.Appendable 接口。scrape.Manager 结构体._promethus scrapes

Windows10 Atom安装和运行Python的使用教程(详细)-程序员宅基地

文章浏览阅读2.6w次,点赞19次,收藏85次。目录一、下载Atom二、Atom安装Python相关组件1.检查Python库支持2.安装Python的适合Atom的IDE、UI、Server和运行工具*三、运行代码范例(爬取以杉原杏璃为关键字的百度图片)一、下载Atom1.官网:Atom官网2.打开这个网页,可以看到Atom针对于操作系统Windows7或以上的版本3.下载完成,双击exe4.加..._atom安装

随便推点

php输出文档,php 如何输出csv文档-程序员宅基地

文章浏览阅读111次。如何创建一个CSV文件方法1 - 使用HTTP头至于在Word和Excel,您需要添加头信息到PHP脚本的例子。下面的代码片断创建一个指定的表包括其列名CSV文件。然后会提示用户下载此文件。$table = 'table_name';$outstr = NULL;header("Content-Type: application/csv");header("Content-Disposition:..._content-type", "application/csv

Android——UI篇:ScrollView子View高度变化时自动滚动到底部的问题_android scrollview 子view 高度改变时-程序员宅基地

文章浏览阅读2.5k次,点赞2次,收藏3次。 好久没更新文章了,最近公司项目遇到了一个问题,在我自定义一个组合控件的时候,点几展开后,列表下方的控件显示出来,然后外层的ScrollView居然自动滚动到了底部,虽然很纳闷为什么会出现这个问题,但是还是的解决啊,毕竟咱们程序员生来就是解决bug的。 找了很多文章,网上也有很多的答案,试过不少,但是都不管用,后来还是让我找到一个很有效的解决方法,那就是自定义Scrol..._android scrollview 子view 高度改变时

ubuntu怎么卸载matlab,卸载Ubuntu下Matlab (uninstall matlab2009 for linux)-程序员宅基地

文章浏览阅读422次。2.在/var目录搜索lm,我只找到以lm-sensors开头的文件,而lm-sensors是一个硬件状况监视器,用来得到温度、电压、风扇速度传感器信我在matlab官网搜到如下帮助文档Problem Description:I would like to uninstall MATLAB on a UNIX or Linux machine.Solution:There is not unins..._ubantu 无法移除matlab

运算放大器的关键指标详解二(噪声)_运放pid电路的噪声-程序员宅基地

文章浏览阅读2.1w次,点赞43次,收藏192次。噪声指标(Noise)一个正常工作的放大电路,当输入端接地时,用示波器观察输出,你看到的可能不是平直的细线,而是在一定幅度之内的杂乱无章的波形。这就是噪声。 你在示波器上看到线越粗,就说明噪声幅度越大。放大电路的输出端噪声,小至 μV 以下,大至百 mV 以上,完全取决于电路设计,能否在示波器上看见,则取决于示波器选择和设置。噪声定义:1) 它的波形在任意时刻都是不确定的,因此它是广谱的,有低频也有高频;2) 它的幅度又是有限制的,这与数学上的高斯分布近似但不完全一致;3) 它具有无限积分趋零性_运放pid电路的噪声

数据分析案例分析:日化公司社群营销场景,产品SKU,用户转化率,用户流转地图_leads数-程序员宅基地

文章浏览阅读3k次。近期参加了一个业务数据分析的3天课程,锻炼自己的业务实例数据分析能力。接下来的内容是第一天课程的作业,里面涉及到许多自己的知识盲区(社群营销,产品SKU,用户转化率,用户流转地图)。分享在这里,期待感兴趣的同志们多多指点~目录作业要求问题分析背景分析概念厘清1. 社群营销是什么?拉群卖货吗?2. 产品SKU3. 用户转化率Q2为什么展示后4张图(图6-图9)【作业点评总结Q2】Q1 从图中看,存在什么问题,出现这些问题的原因是什么Step1. 分..._leads数

数据库多维度水平切分设想 --- 分库,分表,多维度,水平切分,mysql,负载均衡_ssas 加入维度后数据没有切分-程序员宅基地

文章浏览阅读3k次。随着互联网应用的普及,海量数据存储早已经成了大型网站技术人员关注的焦点。每天上亿的访问量对数据库的压力可想而知。因此,为了维持数据库的稳定性和可扩展性,我们常常选择在业务垂直切分的基础上(抽象出业务中心单元如用户中心),再进行数据库的水平切分。 那么为什么要进行数据库的水平切分呢?有些人会说,如果单台数据库服务器过载过高,则可以采用replication的机制,分别指定读写服务器实现读写_ssas 加入维度后数据没有切分

推荐文章

热门文章

相关标签