""" 本次实训任务为应用分段线性变化对直方图进行修改,以卡通图像的图片为例,你需要首先读入图片,对图像矩阵进行像素阈值的分段线性变化,…
- User
""" 本次实训任务为应用分段线性变化对直方图进行修改,以卡通图像的图片为例,你需要首先读入图片,对图像矩阵进行像素阈值的分段线性变化, 得到新的一副线性变化后的图像,再进行计算和绘制直方图,在这里考核的重点是对直方图的峰值(最大值)的输出,你需要分别输出原图和 改变后的图像的峰值(最大值),因为一副图像可以唯一确定一副直方图,该直方图的峰值(最大值)也是被唯一被确定的。所以根据提示, 完善相应代码,相信你一定可以的。 """ import cv2 import numpy as np import matplotlib.pyplot as plt #灰度图图像直方图的输出 def grayHist(img,filename): plt.figure(filename, figsize=(16, 8)) # 展示输入图像 plt.subplot(121) plt.imshow(img,'gray') # 展示直方图 plt.subplot(122) h, w = img.shape[:2] ########## Begin ########## """ 任务1.将二维图像矩阵reshape()为一维数组,返回值为pixelSequence """
########## End ########## #将二维图像矩阵reshape()为一维数组 numberBins = 256 ########## Begin ########## """ 任务2.调用hist()的方法进行直方图的绘制,返回值有histogram, bins, patch """
########## End ########## print(max(histogram)) plt.xlabel("gray label") plt.ylabel("number of pixels") plt.axis([0, 255, 0, np.max(histogram)]) #打印输出峰值 plt.savefig(filename) plt.show() if name=='main': #定义图像数据的路径 img_path='histogram/step6/img_data/ex_1.jpg' out_path = 'histogram/step6/stu_img/step6_plt.jpg' out2_path = 'histogram/step6/stu_img/step6_2_plt.jpg'
img = cv2.imread(img_path, 0) h, w = img.shape[:2] out = np.zeros(img.shape, np.uint8) ########## Begin ########## """ 任务3.通过遍历对不同像素范围内进行分段线性变化,在这里分三段函数进行分段线性变化,主要还是考察for循环的应用 #y=0.5x(x<50) #y=3.6x-310(50<=x<150) #y=0.238*x+194(x>=150) """
########## End ########## out = np.around(out) out = out.astype(np.uint8) grayHist(img,out_path) grayHist(out,out2_path)
- Assistant
import cv2 import numpy as np import matplotlib.pyplot as plt
def grayHist(img, filename): plt.figure(filename, figsize=(16, 8)) plt.subplot(121) plt.imshow(img, 'gray') plt.subplot(122) h, w = img.shape[:2]
pixelSequence = img.reshape(-1) histogram, bins, patch = plt.hist(pixelSequence, bins=range(257)) print(np.max(histogram)) plt.xlabel("gray label") plt.ylabel("number of pixels") plt.axis([0, 255, 0, np.max(histogram)]) plt.savefig(filename) plt.show()if name == 'main': img_path = 'histogram/step6/img_data/ex_1.jpg' out_path = 'histogram/step6/stu_img/step6_plt.jpg' out2_path = 'histogram/step6/stu_img/step6_2_plt.jpg'
img = cv2.imread(img_path, 0) h, w = img.shape[:2] out = np.zeros(img.shape, np.uint8) for i in range(h): for j in range(w): if img[i, j] < 50: out[i, j] = 0.5 * img[i, j] elif img[i, j] >= 150: out[i, j] = 0.238 * img[i, j] + 194 else: out[i, j] = 3.6 * img[i, j] - 310 out = np.around(out) out = out.astype(np.uint8) grayHist(img, out_path) grayHist(out, out2_path)