永久性添加某个库:
!mkdir /home/aistudio/external-libraries
!pip install beautifulsoup4 -t /home/aistudio/external-libraries
使用:
import sys
sys.path.append('/home/aistudio/external-libraries')
统计灰度直方图:
(1)怎么将图像灰度化:
代码:
1.
import numpy as np
import matplotlib.pyplot as plt
import cv2
# 灰度化
img = cv2.imread("lenna.png")
h, w = img.shape[:2] # 获取图片的high和wide
img_gray = np.zeros([h, w], img.dtype) # 创建一张和当前图片大小一样的单通道图片
for i in range(h):
for j in range(w):
m = img[i, j] # 取出当前high和wide中的BGR坐标
img_gray[i, j] = int(m[0] * 0.11 + m[1] * 0.59 + m[2] * 0.3) # 将BGR坐标转化为gray坐标并赋值给新图像
print(img_gray[2,1])
# 二值化
img_binary = np.where(img_gray/255 >= 0.5, 1, 0)
# 画图
img = plt.imread("lenna.png")
plt.subplot(221)
plt.imshow(img)
plt.title('Color map')
plt.subplot(222)
plt.imshow(img_gray, cmap='gray')
plt.title('gray')
plt.subplot(223)
plt.imshow(img_binary, cmap='gray')
plt.title('img_binary')
plt.savefig('mytestplt.png')
plt.show()
2.用第三方库:
# 灰度化
#img_gray = rgb2gray(img) # 此函数做灰度化,返回的数值范围为0-1.所以在做二值化的时候无需除以255
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 因为imread读进来的是BGR数据,所以这里做BGR转GRAY
# 二值化
img_binary = np.where(img_gray/255 >= 0.5, 1, 0)
(2):
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('data/nezha.jpg',1)#1是彩色图像
img1=img
plt.subplot(211)
plt.hist(img.reshape(-1),256,[0,256])
plt.show()
plt.subplot(212)
plt.hist(img1.reshape(-1),256,[0,256],edgecolor='r')
plt.show()
(3)
import cv2
# import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('data/nezha.jpg',0)
histr = cv2.calcHist([img],[0],None,[256],[0,256]) #channels==0意思是用图像编码的通道数,默认为零#hist是一个shape为(256,1)的数组,表示0-255每个像素值对应的像素个数,下标即为相应的像素值
plt.plot(histr,color = 'b')
plt.xlim([0,256])
plt.show()
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('data/nezha.jpg',1)
color = ('b','g','r')
for i,col in enumerate(color):#i为下标,col为颜色
histr = cv2.calcHist([img],[i],None,[256],[0,256])
#hist是一个shape为(256,1)的数组,表示0-255每个像素值对应的像素个数,下标即为相应的像素值
plt.plot(histr,color = col)
plt.xlim([0,256])
plt.show()
总体:
import sys
import numpy as np
import cv2
import matplotlib.pyplot as plt
def main():
img=cv2.imread('data/nezha.jpg',0)
#得到计算灰度直方图的值
n = np.array(img)
xy=xygray(img)
#画出灰度直方图
x_range=range(256)
plt.plot(x_range,xy,"r",linewidth=2,c='black')
#设置坐标轴的范围
y_maxValue=np.max(xy)
plt.axis([0,255,0,y_maxValue])
#设置坐标轴的标签
plt.xlabel('gray Level')
plt.ylabel("number of pixels")
plt.show()
def xygray(img):
#得到高和宽
rows,cols=img.shape
print(img.shape)
#存储灰度直方图
print(img.dtype)
xy=np.zeros([256],np.uint64)
for r in range(rows):
for c in range(cols):
xy[img[r][c]] += 1
#返回一维ndarry
print(xy.sum())
return xy
main()