我在Python方面没有任何经验,但我需要将其作为项目的数据处理步骤.我正在处理葡萄园的无人机热图像,目标是根据海拔和温度将树冠像素与地面像素分离.使用DEM(数字高程模型),首先对冠层和地面进行了区分.这就产生了一个二元掩模层,可以放在葡萄园的热图像上.这样,我现在有了一个Python中的热图像,其中大多数地面像素为0,树冠像素的值在0到65535之间,表示温度.然而,由于第一次区分(使用DEM)不够精确,一些地面像素也包含在树冠遮罩中.

现在,我想利用所选区域的温度进行第二次区分.我能够用opencv绘制所有树冠区域的轮廓(因此我有一个完整的列表,其中包含代表树冠区域的所有轮廓,以及一些地面像素).我的目标是 for each 轮廓区域制作一个直方图,显示该区域内每个像素值的密度.希望我可以删除过热的像素(即地面像素).

有人知道如何为图像的每个(填充的)轮廓生成直方图吗?现在的格式是6082x4922 Ndaray,其值介于0和65535之间,数据类型为uint16.我使用PyCharm作为IDE.

提前感谢!

推荐答案

Approach:

  • 迭代遮罩中的每个轮廓
  • 查找遮罩中存在的像素的位置
  • 在给定图像中找到相应的值
  • 计算并绘制直方图

Code:

# reading given image in grayscale
img = cv2.imread('apples.jpg', 0)

enter image description here

# reading the mask in grayscale
img_mask = cv2.imread(r'apples_mask.jpg', 0)
# binarizing the mask
mask = cv2.threshold(img_mask,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

enter image description here

# find contours on the mask
contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# the approach is encoded within this loop
for i, c in enumerate(contours):
    # create a blank image of same shape
    black = np.full(shape = im.shape, fill_value = 0, dtype = np.uint8)
    # draw a single contour as a mask
    single_object_mask = cv2.drawContours(black,[c],0,255, -1)
    # coordinates containing white pixels of mask
    coords = np.where(single_object_mask == 255)
    # pixel intensities present within the image at these locations
    pixels = img[coords]
    # plot histogram
    plt.hist(pixels,256,[0,256])
    plt.savefig('apples_histogram_{}.jpg'.format(i)')
    # to avoid plotting in the same plot
    plt.clf()

Result: (the following are the 3 histogram plots)

enter image description here

enter image description here

enter image description here

如果删除plt.clf(),所有直方图将绘制在一个绘图上

您可以为您的用例扩展相同的方法

原始图像:

enter image description here

Python相关问答推荐

如何才能将每个组比上一组增加N %?

LAB中的增强数组

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

Pandas - groupby字符串字段并按时间范围 Select

在Mac上安装ipython

对象的`__call__`方法的setattr在Python中不起作用'

pandas:排序多级列

将JSON对象转换为Dataframe

未知依赖项pin—1阻止conda安装""

如何并行化/加速并行numba代码?

如何指定列数据类型

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

Tkinter菜单自发添加额外项目

ConversationalRetrivalChain引发键错误

从列表中获取n个元素,其中list [i][0]== value''

交替字符串位置的正则表达式

巨 Python :逆向猜谜游戏

如何在Python Pandas中填充外部连接后的列中填充DDL值

在用于Python的Bokeh包中设置按钮的样式

什么是一种快速而优雅的方式来转换一个包含一串重复的列,而不对同一个值多次运行转换,