Python将像素值映射到它';带cv2的s直方图箱
给定一幅图像,有没有一种快速的方法将像素值映射到它的binPython将像素值映射到它';带cv2的s直方图箱,python,cv2,Python,Cv2,给定一幅图像,有没有一种快速的方法将像素值映射到它的bin img = cv2.imread('test_image.jpg') hist_g = cv2.calcHist([img[x:x+w,y:y+h,:]], [1], None, [9], [0, 256]) 这将返回一个9x1数组,该数组包含从0到256的9个像素点。我想 我想要的是[x:x+w,y:y+h]矩阵,每个条目都有像素映射到的箱子编号。我该怎么做 例如,假设我有矩阵 x = np.array([[154, 192],[6
img = cv2.imread('test_image.jpg')
hist_g = cv2.calcHist([img[x:x+w,y:y+h,:]], [1], None, [9], [0, 256])
这将返回一个9x1数组,该数组包含从0到256的9个像素点。我想
我想要的是[x:x+w,y:y+h]
矩阵,每个条目都有像素映射到的箱子编号。我该怎么做
例如,假设我有矩阵
x = np.array([[154, 192],[67,115]])
x_histcounts = np.array([[5, 7],[3,4]])
我想把矩阵还给你
x = np.array([[154, 192],[67,115]])
x_histcounts = np.array([[5, 7],[3,4]])
基于cv2.calcHist([img[x:x+w,y:y+h,:],[1],无[9],[0256])
由于154位于第5个存储箱中,192位于第7个存储箱中,依此类推。如果要将像素映射到
9
存储箱,则可以转换为灰度,然后使用/
除以(256/9)
以获得整数
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
result = img_gray[x:x+w,y:y+h] // (256/9)
在
calcHist
中,您使用通道列表[1]
,因此您只需要一个通道的直方图,这意味着您不必转换为灰度,而是使用[…,…,1]
result = img[x:x+w, y:y+h, 1] // (256/9)
编辑:我测试了您的示例数据
[[154192],[67115]
,它给了我
[[5,6],[2,4]]
而不是[[5,7],[3,4]]
import numpy as np
bins_number = 9
x = np.array([[154, 192], [67, 115]])
result = (x // (256/bins_number)).astype(int)
print('result:', result.tolist())
使用Google“numpy histcounts matlab”
我还找到了使用np.digitize()
复制histcounts
的工具,它也给了我[[5,6],[2,4]
而不是[[5,7],[3,4]]
,但我不知道我是否正确地创建了垃圾箱范围
import numpy as np
bins_number = 9
x = np.array([[154, 192], [67, 115]])
bins = [(256/bins_number)*x for x in range(1, bins_number+1)]
result = np.digitize(x, bins)
print('result:', result.tolist())
print('bins:', bins)
我没有Matlab
,所以我尝试在中使用histc()
它也给了我[[5,6],[2,4]]
而不是[[5,7],[3,4]
import numpy as np
bins_number = 9
x = np.array([[154, 192], [67, 115]])
result = (x // (256/bins_number)).astype(int)
print('result:', result.tolist())
编辑:我发现要生成箱子范围
import numpy as np
bins_number = 9
x = np.array([[154, 192], [67, 115], [0,1]])
bins = np.histogram_bin_edges(x, bins=9, range=(0, 256))
print('bins:', bins)
但是它添加了0
作为第一条边,因此以后它使用数字1-9
而不是0-8
,但是如果使用bin[1:][/code>,那么它仍然使用数字0-8
import numpy as np
bins_number = 9
x = np.array([[154, 192], [67, 115]])
bins = np.histogram_bin_edges(x, bins=9, range=(0, 255))
print('bins:', bins)
print('result:', np.digitize(x, bins[1:]).tolist())
我不明白你想做什么,但9x1
是直方图的正确大小。矩阵[x:x+w,y:y+h]
不是直方图。似乎您更应该使用将每个值除以9得到整数值来得到您期望的结果。类似于result=img[x:x+w,y:y+h,:][/9
我澄清了这个问题。我基本上想要一个Matlab拥有的histcounts方法。我的代码对示例数据给出了几乎相同的结果。我的代码向下舍入(地板),但您的数据向上舍入(屋顶)或舍入到最接近的整数。我添加了有关numpy.histogram\u bin\u edges的信息