圖像灰度化與二值化

圖像灰度化

什么是圖像灰度化?

圖像灰度化并不是將單純的圖像變成灰色,而是將圖片的BGR各通道以某種規律綜合起來,使圖片顯示位灰色。
規律如下:
在這里插入圖片描述

手動實現灰度化

首先我們采用手動灰度化的方式:
其思想就是:
先創建一個跟原來長寬一樣的空白圖片,然后將原圖片中圖片各個像素按照下面公式填入圖片中,實現灰度化。
在這里插入圖片描述

import cv2
import numpy as np
from skimage.color import rgb2gray
from PIL import Image
import matplotlib.pyplot as pltimg = cv2.imread("lenna.png")   #opencv讀取圖像
#img = plt.imread("lenna.png")  #matlab讀取圖像
h,w = img.shape[:2] #讀出圖像的長寬
img_gray = np.zeros([h,w],img.dtype)    #創建一個與當前圖像相同長寬的單通道圖片
for i in range(h):for j in range(w):m = img[i,j]img_gray[i,j] = int(m[0]*0.11+m[1]*0.59+m[2]*0.3)   #將CV讀取的BGR轉化為gray值給新圖像print(img_gray)
cv2.imshow('gray picture ',img_gray)    #cv展示灰色圖像
cv2.waitKey (0) #如果不寫等待時間,圖像會一閃而過

skimage實現圖像灰度化

img = cv2.imread("lenna.png")
img_gray = rgb2gray(img)
cv2.imshow('gray picture ',img_gray)
cv2.waitKey (0)

opencv實現圖像灰度化

img = cv2.imread("lenna.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#用opencv輸出
cv2.imshow('gray picture ',img_gray)
cv2.waitKey (0)#用plt輸出:這里要注意,cmap為顏色圖譜,默認為RGB(A)顏色空間,也可以指定,gray是灰度圖,若cmap為其他會造成色差
plt.imshow(img_gray,cmap="gray")
plt.show()

圖像二值化

什么是圖像二值化?

所謂圖像二值化,就是將圖像中像素點的值取其中間值,若大于中間值,則將該像素點的值設為最大值,若小于中間值,則把該像素點設為最小值。使整個圖片最后只存在兩個值:最大值和最小值。

手動實現二值化

img = plt.imread("lenna.png")
img_gray = rgb2gray(img)	#這里還是要先灰度化
rows, cols = img_gray.shape
for i in range(rows):for j in range(cols):if (img_gray[i, j] <= 0.5):img_gray[i, j] = 0else:img_gray[i, j] = 1plt.imshow(img_gray,cmap="gray")
plt.show()

numpy實現圖像二值化

img = plt.imread("lenna.png")
img_gray = rgb2gray(img)#這里還是要先灰度化img_binary = np.where(img_gray >= 0.5, 1, 0)
plt.imshow(img_binary,cmap="gray")
plt.show()

opencv實現圖像二值化

img = cv2.imread("lenna.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#這里還是要先灰度化cv2.threshold(img_gray,127,255,0,img_gray)
cv2.imshow('img_binary',img_gray)
cv2.waitKey(0)

全部代碼與實現結果:

全部代碼:

import cv2
import numpy as np
from skimage.color import rgb2gray
from PIL import Image
import matplotlib.pyplot as plt"""
手動實現圖像灰度化
"""img = cv2.imread("lenna.png")   #opencv讀取圖像
#img = plt.imread("lenna.png")  #matlab讀取圖像
h,w = img.shape[:2] #讀出圖像的長寬
img_gray = np.zeros([h,w],img.dtype)    #創建一個與當前圖像相同長寬的單通道圖片
for i in range(h):for j in range(w):m = img[i,j]img_gray[i,j] = int(m[0]*0.11+m[1]*0.59+m[2]*0.3)   #將CV讀取的BGR轉化為gray值給新圖像,注意:這個公式是內定的print(img_gray)
cv2.imshow('gray picture ',img_gray)    #cv展示灰色圖像
cv2.waitKey (0) #如果不寫等待時間,圖像會一閃而過"""
skimage實現圖像灰度化
"""img = cv2.imread("lenna.png")
img_gray = rgb2gray(img)
cv2.imshow('gray picture ',img_gray)
cv2.waitKey (0)"""
opencv實現圖像灰度化
"""img = cv2.imread("lenna.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#用opencv輸出
cv2.imshow('gray picture ',img_gray)
cv2.waitKey (0)plt.imshow(img_gray,cmap="gray")
plt.show()"""
手動圖像二值化
"""
img = plt.imread("lenna.png")
img_gray = rgb2gray(img)
rows, cols = img_gray.shape
for i in range(rows):for j in range(cols):if (img_gray[i, j] <= 0.5):img_gray[i, j] = 0else:img_gray[i, j] = 1plt.imshow(img_gray,cmap="gray")
plt.show()"""
numpy實現圖像二值化
"""
img = plt.imread("lenna.png")
img_gray = rgb2gray(img)
img_binary = np.where(img_gray >= 0.5, 1, 0)
plt.imshow(img_binary,cmap="gray")
plt.show()"""
opencv實現圖像二值化
"""img = cv2.imread("lenna.png")
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.threshold(img_gray,127,255,0,img_gray)
cv2.imshow('img_binary',img_gray)
cv2.waitKey(0)

實現結果:

原圖:
在這里插入圖片描述
灰度化:
在這里插入圖片描述
二值化:
在這里插入圖片描述

思考與問題:

1.二值化中plt與cv閾值不同問題:

在plt讀取圖像之后,圖像的每一個像素值都在[0,1]之間,在之后的cv2讀取的圖像,每一個像素值在[0,255]之間,所以在二值化時,plt是閾值為0.5,像素值分成0或1,而cv2中閾值是127,像素值分為0或255。

2.plt與cv交叉讀取數據會出現圖像失真問題:

因為 opencv 的接口使用BGR模式,而 matplotlib.pyplot 接口使用的是RGB模式
解決方法是:
在cv輸入圖像后把通道順序變換一下,就在cv2.imread輸入后面添加

b, g, r = cv2.split(img)
img = cv2.merge([r, g, b])

3.在灰度化和二值化圖像用plt輸出的時候必須添加cmap = ‘gray’,如果圖像會失真

用plt輸出中cmap為顏色圖譜,默認為RGB(A)顏色空間,也可以指定,gray是灰度圖,若cmap為其他會造成色差

4.CV或者plt打印圖像時很快消失:

無論誰cv輸出還是plt輸出的最后的結尾都需要加上cv.waitkey(0)或者plt.show()不然輸出圖像轉瞬即逝,很快就消失了,不能長時間停留。

5.PLT和openCV讀取和輸出方法:

PLT:

#輸入
img = plt.imread("lenna.png")
#輸出
plt.imshow(img,cmap="gray")
plt.show()

CV:

#輸入
img = cv2.imread("lenna.png")
#輸出
cv2.imshow('img',img_gray)
cv2.waitKey(0)

這里注意:cv2的輸出必須有標題,不然會報錯。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/389398.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/389398.shtml
英文地址,請注明出處:http://en.pswp.cn/news/389398.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

分析citibike數據eda

數據科學 (Data Science) CitiBike is New York City’s famous bike rental company and the largest in the USA. CitiBike launched in May 2013 and has become an essential part of the transportation network. They make commute fun, efficient, and affordable — no…

jvm感知docker容器參數

docker中的jvm檢測到的是宿主機的內存信息&#xff0c;它無法感知容器的資源上限&#xff0c;這樣可能會導致意外的情況。 -m參數用于限制容器使用內存的大小&#xff0c;超過大小時會被OOMKilled。 -Xmx: 默認為物理內存的1/4。 4核CPU16G內存的宿主機 java 7 docker run -m …

Flask之flask-script 指定端口

簡介 Flask-Scropt插件為在Flask里編寫額外的腳本提供了支持。這包括運行一個開發服務器&#xff0c;一個定制的Python命令行&#xff0c;用于執行初始化數據庫、定時任務和其他屬于web應用之外的命令行任務的腳本。 安裝 用命令pip和easy_install安裝&#xff1a; pip install…

上采樣(放大圖像)和下采樣(縮小圖像)(最鄰近插值和雙線性插值的理解和實現)

上采樣和下采樣 什么是上采樣和下采樣&#xff1f; ? 縮小圖像&#xff08;或稱為下采樣&#xff08;subsampled&#xff09;或降采樣&#xff08;downsampled&#xff09;&#xff09;的主要目的有 兩個&#xff1a;1、使得圖像符合顯示區域的大小&#xff1b;2、生成對應圖…

r語言繪制雷達圖_用r繪制雷達蜘蛛圖

r語言繪制雷達圖I’ve tried several different types of NBA analytical articles within my readership who are a group of true fans of basketball. I found that the most popular articles are not those with state-of-the-art machine learning technologies, but tho…

java 分裂數字_分裂的補充:超越數字,打印物理可視化

java 分裂數字As noted in my earlier Nightingale writings, color harmony is the process of choosing colors on a Color Wheel that work well together in the composition of an image. Today, I will step further into color theory by discussing the Split Compleme…

Java 集合 之 Vector

http://www.verejava.com/?id17159974203844 import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Vector;public class Test {/*** param args the command line arguments*/public static void main(String[] args) {//打印…

前端電子書單大分享~~~

前言 純福利&#xff0c; 如果你不想買很多書&#xff0c;只想省錢看電子書&#xff1b; 如果你找不到很多想看書籍的電子書版本&#xff1b; 那么&#xff0c;請保存或者下載到自己的電腦或者手機或者網盤吧。 不要太著急&#xff0c;連接在最后呢 前端 前端框架 node html-cs…

結構化數據建模——titanic數據集的模型建立和訓練(Pytorch版)

本文參考《20天吃透Pytorch》來實現titanic數據集的模型建立和訓練 在書中理論的同時加入自己的理解。 一&#xff0c;準備數據 數據加載 titanic數據集的目標是根據乘客信息預測他們在Titanic號撞擊冰山沉沒后能否生存。 結構化數據一般會使用Pandas中的DataFrame進行預處理…

比賽,幸福度_幸福與生活滿意度

比賽,幸福度What is the purpose of life? Is that to be happy? Why people go through all the pain and hardship? Is it to achieve happiness in some way?人生的目的是什么&#xff1f; 那是幸福嗎&#xff1f; 人們為什么要經歷所有的痛苦和磨難&#xff1f; 是通過…

帶有postgres和jupyter筆記本的Titanic數據集

PostgreSQL is a powerful, open source object-relational database system with over 30 years of active development that has earned it a strong reputation for reliability, feature robustness, and performance.PostgreSQL是一個功能強大的開源對象關系數據庫系統&am…

Django學習--數據庫同步操作技巧

同步數據庫&#xff1a;使用上述兩條命令同步數據庫1.認識migrations目錄&#xff1a;migrations目錄作用&#xff1a;用來存放通過makemigrations命令生成的數據庫腳本&#xff0c;里面的生成的腳本不要輕易修改。要正常的使用數據庫同步的功能&#xff0c;app目錄下必須要有m…

《20天吃透Pytorch》Pytorch自動微分機制學習

自動微分機制 Pytorch一般通過反向傳播 backward 方法 實現這種求梯度計算。該方法求得的梯度將存在對應自變量張量的grad屬性下。 除此之外&#xff0c;也能夠調用torch.autograd.grad 函數來實現求梯度計算。 這就是Pytorch的自動微分機制。 一&#xff0c;利用backward方…

React 新 Context API 在前端狀態管理的實踐

2019獨角獸企業重金招聘Python工程師標準>>> 本文轉載至&#xff1a;今日頭條技術博客 眾所周知&#xff0c;React的單向數據流模式導致狀態只能一級一級的由父組件傳遞到子組件&#xff0c;在大中型應用中較為繁瑣不好管理&#xff0c;通常我們需要使用Redux來幫助…

機器學習模型 非線性模型_機器學習模型說明

機器學習模型 非線性模型A Case Study of Shap and pdp using Diabetes dataset使用糖尿病數據集對Shap和pdp進行案例研究 Explaining Machine Learning Models has always been a difficult concept to comprehend in which model results and performance stay black box (h…

5分鐘內完成胸部CT掃描機器學習

This post provides an overview of chest CT scan machine learning organized by clinical goal, data representation, task, and model.這篇文章按臨床目標&#xff0c;數據表示&#xff0c;任務和模型組織了胸部CT掃描機器學習的概述。 A chest CT scan is a grayscale 3…

Pytorch高階API示范——線性回歸模型

本文與《20天吃透Pytorch》有所不同&#xff0c;《20天吃透Pytorch》中是繼承之前的模型進行擬合&#xff0c;本文是單獨建立網絡進行擬合。 代碼實現&#xff1a; import torch import numpy as np import matplotlib.pyplot as plt import pandas as pd from torch import …

vue 上傳圖片限制大小和格式

<div class"upload-box clear"><span class"fl">上傳圖片</span><div class"artistDet-logo-box fl"><el-upload :action"this.baseServerUrl/fileUpload/uploadPic?filepathartwork" list-type"pic…

作業要求 20181023-3 每周例行報告

本周要求參見&#xff1a;https://edu.cnblogs.com/campus/nenu/2018fall/homework/2282 1、本周PSP 總計&#xff1a;927min 2、本周進度條 代碼行數 博文字數 用到的軟件工程知識點 217 757 PSP、版本控制 3、累積進度圖 &#xff08;1&#xff09;累積代碼折線圖 &…

算命數據_未來的數據科學家或算命精神向導

算命數據Real Estate Sale Prices, Regression, and Classification: Data Science is the Future of Fortune Telling房地產銷售價格&#xff0c;回歸和分類&#xff1a;數據科學是算命的未來 As we all know, I am unusually blessed with totally-real psychic abilities.眾…