python 图片灰度化 opencv-python

1、简介

opencv是一个强大的图像处理和计算机视觉库,实现了很多实用算法,而opencv-python是OpenCV的python接口。直接安装opencv-python包(非官方):

 pip install opencv-python

2、知识点

图片都是像素点

图片是由一个一个的像素点组成的,像素是图像的最小单元,我们右键——>属性去查看图片的信息,看到图片的尺寸如下图:即宽度是372个像素,高度也是300个像素,也就是说这张图片是由一个372 * 300的像素点矩阵构成的,这个矩阵是372行,300列,共有372 * 300 = 111600个像素点。

图片的像素信息

绝大部分图片是 RGB 类型的,即是用RGB(红绿蓝)三原色组成的图片。在图像处理中,用RGB三个分量(R:Red,G:Green,B:Blue),即红、绿、蓝三原色来表示真彩色,R分量,G分量,B分量的取值范围均为0~255,比如电脑屏幕上的一个红色的像素点的三个分量的值分别为:255,0,0

3、图片灰度化

什么叫图片的灰度化呢?其实很简单,就是让像素点矩阵中的每一个像素点都满足下面的关系:R=G=B(就是红色变量的值,绿色变量的值,和蓝色变量的值,这三个值相等),此时的这个值叫做灰度值。

理解一张图片是由一个像素点矩阵构成,就知道我们对图像的处理就是对这个像素点矩阵的操作,想要改变某个像素点的颜色,只要在这个像素点矩阵中找到这个像素点的位置,比如第x行,第y列,所以这个像素点在这个像素点矩阵中的位置就可以表示成(x,y),因为一个像素点的颜色由红、绿、蓝三个颜色变量表示,所以我们通过给这三个变量赋值,来改变这个像素点的颜色,比如改成红色(255,0,0),可以表示为(x,y,(R=255,G=0,B=0))x行y列的像素值为(255,0,0)。

平均值法:

是转化后R,G,B的值为转化前R,G,B的平均值

灰度化后的R=(处理前的R + 处理前的G +处理前的B)/ 3
灰度化后的G=(处理前的R + 处理前的G +处理前的B)/ 3
灰度化后的B=(处理前的R + 处理前的G +处理前的B)/ 3

加权平均法(处理效果最好):

按照一定权值,对R,G,B的值加权平均

灰度化后的R =  处理前的R * 0.3+ 处理前的G * 0.59 +处理前的B * 0.11
灰度化后的G =  处理前的R * 0.3+ 处理前的G * 0.59 +处理前的B * 0.11
灰度化后的B =  处理前的R * 0.3+ 处理前的G * 0.59 +处理前的B * 0.11

最大值发:

使转化后的R,G,B得值等于转化前3个值中最大的一个

   灰度化后的R、G、B=处理前的R、G、B中的最大值

4、代码示例

# 先加载一张图片 打印它的一些关键信息
image = cv.imread("C:/path/to/image/doge.png")
print(image.shape) # (372, 300, 3)
print(image.size) # 334800
print(image.dtype) # uint8
def gray_by_max():
    # 最大值法:使转化后的R,G,B得值等于转化前3个值中最大的一个,即: R=G=B=max(R,G,B)这种方法转换的灰度图亮度很高。
    dst = np.zeros((image.shape[0], image.shape[1], 1), np.uint8)
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            dst[i, j] = max(image[i, j][0], image[i, j][1], image[i, j][2])
    print(dst)
    cv.imwrite("C:/path/to/image/doget_max_gray.png", dst)
最大灰度法
def gray_by_avg():
    # 平均值法:是转化后R,G,B的值为转化前R,G,B的平均值。即:R=G=B=(R+G+B)/3  这种方法产生的灰度图像比较柔和。
    dst = np.zeros((image.shape[0], image.shape[1], 1), np.uint8)
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            dst[i, j] = (image[i, j][0] + image[i, j][1] + image[i, j][2]) / 3
    print(dst)
    cv.imwrite("C:/path/to/image/doget_avg_gray.png", dst)
平均灰度法
def gray_with_weight():
    # 加权平均值法:按照一定权值,对R,G,B的值加权平均,即:R=G=B=(W(r) * R+ W(g) * G+ W(b) * B),
    # 其中W(x)分别为R,G,B的权值,取不同的值形成不同的灰度图像。由于人眼对绿色最为敏感,红色次之,对蓝色的敏感性最低,因此一般情况下,
    # W(r)=0.299, W(g)=0.587, W(b)=0.114得到的灰度图像效果最好。
    dst = np.zeros((image.shape[0], image.shape[1], 3), np.uint8)
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            dst[i, j] = (0.3 * image[i, j][0] + 0.11 * image[i, j][1] + 0.59 * image[i, j][2])
    print(dst)
    cv.imwrite("C:/path/to/image/doget_weight_gray.png", dst)
加权灰度法

streamlit

streamlit – The fastest way to build and share data apps 是专门针对机器学习和数据科学团队的应用开发框架,你可以认为它的目标是取代Flask在机器学习项目中的地位从而帮助机器学习工程师快速开发用户交互工具。

源码传送门: https://github.com/streamlit/streamlit

关于streamlit的介绍和教程网上可以搜到,不再做过多的冗余介绍,当然本篇依旧是入门篇,不过我们会用实际的数据来看一下它基本的效果。我们要用DogeCoin狗狗币的历史数据来画一些有意思的图,并利用streamlit来展示出来,整个过程也是对streamlit的初步认识。废话不多说,开始撸代码。

1、安装

pip install streamlit

2、狗狗币数据一览

DogeCoin数据一览、

3、引入相关python包

import streamlit as st
import pandas as pd
import plotly.graph_objects as go

4、自定义函数

# 加载数据
def load_dogecoin_data():
    ss = pd.read_csv("D:/path/to/dogecoin/doge_history.csv")
    ss = ss.set_index(pd.DatetimeIndex(ss['tickertime']))
    ss = ss.drop(columns=['Unnamed: 0', 'tickertime'])
    ss = ss.sort_index()
    return ss

# 设置开始结束日期
def get_inputs():
    # 设置边框输入栏
    start_date = st.sidebar.text_input("开始日期:", "2019-12-01")
    end_date = st.sidebar.text_input("结束日期:", "2021-05-16")
    return start_date, end_date

# 按日期加载数据
def get_data(start, end):
    data = load_dogecoin_data()
    start = pd.to_datetime(start)
    end = pd.to_datetime(end)
    return data.loc[start: end]

5、数据初始化

_start, _end = get_inputs()
df = get_data(_start, _end)

6、各种画图

fig = go.Figure(data=[go.Candlestick(
    x=df.index,
    open=df['openprice'],
    close=df['closeprice'],
    high=df['high'],
    low=df['low'],
    increasing_line_color='red',
    decreasing_line_color='green'
)])

st.title('Analysis DogeCoin by Streamlit!')
st.header('DogeCoin data')
st.write(df)
st.header('DogeCoin Statistics')
st.write(df.describe())
st.header('DogeCoin Volume')
st.bar_chart(df['vol'])
st.header('DogeCoin Close Price')
st.line_chart(df['closeprice'])
st.header('DogeCoin Candle Stick')
st.plotly_chart(fig)

7、运行

streamlit run streamlit_app.py

8、效果展示

我们可以在浏览器中看到运行的效果,打开浏览器输入地址,http://localhost:8501/

streamlit sidebar效果

在浏览器的左侧边框可以看到初始化的文本框,我们可以自己手动输入日期,然后按回车,那么浏览器对应的其它图会自动从新加载指定日期的数据。

streamlit 基本效果图标1
streamlit 基本效果图2

整个浏览器中看到的图都是动态的,可以通过鼠标滚动或者单击挪动图的具体内容。

参考: https://zhuanlan.zhihu.com/p/85741306

Scala 箭头符号使用场景 =>

我们在阅读或者使用Scala语言开发的程序或框架(如Spark)时经常会看到各种箭头符号,有的是单线箭头(-> | <-),而有的是等号箭头(=> ),还有的是双单线箭头(–>),这些符号在Scala的世界里被称为箭头函数,而且同一个箭头函数在不同的场景下是有不同的含义,不同的使用原则的。

本文主要先介绍下等号+方向符号的箭头函数 => 的用法

1、匿名函数

var mul = (x: Int, y: Int) => x + y
println(mul(3, 4)) //7

模式匹配(match…case)

  def TestMatch(x: Int): String = x match {
    case 1 => "one"
    case 2 => "two"
    case _ => "others"
  }
  println(TestMatch(3))