第三章 3.1 表示图像 理解灰度图、RGB图和数组的关系

图片与脚本文件放在一个文件夹内,同级。

图片网上找一个就可以了。

复制代码
# https://github.com/PacktPublishing/Modern-Computer-Vision-with-PyTorch
# https://github.com/PacktPublishing/Modern-Computer-Vision-with-PyTorch

###################  Chapter Three #######################################

# 第三章  灰度图和数组

import cv2, matplotlib.pyplot as plt
import os
########################################################################
# 文件路径
file_path = 'meleon.jpg'  #'C:/path/to/your/image/meleon.jpeg'  # 替换为你的图像文件路径

# 检查文件是否存在
if not os.path.exists(file_path):
    print(f"Error: The file {file_path} does not exist.")
else:
    img = cv2.imread('meleon.jpg')
########################################################################
    # 检查图像是否成功读取
    if img is None:
        print("Error: The image could not be read.")
    else:
        # 切片操作
        #img = img[50:250, 40:240]

        # 转换为灰度图像
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # 显示图像
        plt.imshow(img_gray, cmap='gray')
        #plt.show()

        img_gray_small = cv2.resize(img_gray, (16, 24))
        plt.imshow(img_gray_small, cmap='gray')
        print(img_gray_small)
        plt.show()

########################################################################
#彩图与数组
# 文件路径
file_path = 'meleon.jpg'  #'C:/path/to/your/image/meleon.jpeg'  # 替换为你的图像文件路径

# 检查文件是否存在
if not os.path.exists(file_path):
    print(f"Error: The file {file_path} does not exist.")
else:

    img = cv2.imread('meleon.jpg')
    # 检查图像是否成功读取
    if img is None:
        print("Error: The image could not be read.")
    else:
        print(img.shape)
        crop = img[-3:,-3:]
        print(crop)
        plt.imshow(crop)
        plt.show()
########################################################################
复制代码

 

posted @   辛河  阅读(43)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示