[英]How to plot a histogram of extracted image color channels
我正在嘗試制作我的圖像具有的不同通道的直方圖。
而不是制作直方圖,而是出現錯誤"shape mismatch: objects cannot be broadcast to a single shape"
。
以下是我目前擁有的代碼。 關於我做錯了什么的任何想法?
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
im = mpimg.imread('ps09_display-helix.png')
im = im[100:560, 368:864, :]
pl = np.histogram(im)
plt.bar(range(768), pl[:256], color='r', alpha=0.5)
plt.bar(range(768), pl[256:2*256], color='g', alpha=0.4)
plt.bar(range(768), pl[2*256:], color='b', alpha=0.3)
plt.show()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-84-e551a5a26f6e> in <module>
2 im = im[100:560, 368:864, :]
3 pl = np.histogram(im)
----> 4 plt.bar(range(768), pl[:256], color='r', alpha=0.5)
5 plt.bar(range(768), pl[256:2*256], color='g', alpha=0.4)
6 plt.bar(range(768), pl[2*256:], color='b', alpha=0.3)
e:\Anaconda3\lib\site-packages\matplotlib\pyplot.py in bar(x, height, width, bottom, align, data, **kwargs)
2485 x, height, width=0.8, bottom=None, *, align='center',
2486 data=None, **kwargs):
-> 2487 return gca().bar(
2488 x, height, width=width, bottom=bottom, align=align,
2489 **({"data": data} if data is not None else {}), **kwargs)
e:\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1445 def inner(ax, *args, data=None, **kwargs):
1446 if data is None:
-> 1447 return func(ax, *map(sanitize_sequence, args), **kwargs)
1448
1449 bound = new_sig.bind(ax, *args, **kwargs)
e:\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bar(self, x, height, width, bottom, align, **kwargs)
2428 yerr = self._convert_dx(yerr, y0, y, self.convert_yunits)
2429
-> 2430 x, height, width, y, linewidth = np.broadcast_arrays(
2431 # Make args iterable too.
2432 np.atleast_1d(x), height, width, y, linewidth)
<__array_function__ internals> in broadcast_arrays(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in broadcast_arrays(subok, *args)
536 args = [np.array(_m, copy=False, subok=subok) for _m in args]
537
--> 538 shape = _broadcast_shape(*args)
539
540 if all(array.shape == shape for array in args):
e:\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in _broadcast_shape(*args)
418 # use the old-iterator because np.nditer does not handle size 0 arrays
419 # consistently
--> 420 b = np.broadcast(*args[:32])
421 # unfortunately, it cannot handle 32 or more arguments directly
422 for pos in range(32, len(args), 31):
ValueError: shape mismatch: objects cannot be broadcast to a single shape
所以我正在嘗試制作我的圖像具有的不同通道的直方圖。 而不是制作直方圖,而是出現錯誤“形狀不匹配:對象無法廣播到單個形狀”。 以下是我目前擁有的代碼。 關於我做錯了什么的任何想法?
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
im = mpimg.imread('ps09_display-helix.png')
im = im[100:560, 368:864, :]
pl = np.histogram(im)
plt.bar(range(768), pl[:256], color='r', alpha=0.5)
plt.bar(range(768), pl[256:2*256], color='g', alpha=0.4)
plt.bar(range(768), pl[2*256:], color='b', alpha=0.3)
plt.show()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-84-e551a5a26f6e> in <module>
2 im = im[100:560, 368:864, :]
3 pl = np.histogram(im)
----> 4 plt.bar(range(768), pl[:256], color='r', alpha=0.5)
5 plt.bar(range(768), pl[256:2*256], color='g', alpha=0.4)
6 plt.bar(range(768), pl[2*256:], color='b', alpha=0.3)
e:\Anaconda3\lib\site-packages\matplotlib\pyplot.py in bar(x, height, width, bottom, align, data, **kwargs)
2485 x, height, width=0.8, bottom=None, *, align='center',
2486 data=None, **kwargs):
-> 2487 return gca().bar(
2488 x, height, width=width, bottom=bottom, align=align,
2489 **({"data": data} if data is not None else {}), **kwargs)
e:\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1445 def inner(ax, *args, data=None, **kwargs):
1446 if data is None:
-> 1447 return func(ax, *map(sanitize_sequence, args), **kwargs)
1448
1449 bound = new_sig.bind(ax, *args, **kwargs)
e:\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in bar(self, x, height, width, bottom, align, **kwargs)
2428 yerr = self._convert_dx(yerr, y0, y, self.convert_yunits)
2429
-> 2430 x, height, width, y, linewidth = np.broadcast_arrays(
2431 # Make args iterable too.
2432 np.atleast_1d(x), height, width, y, linewidth)
<__array_function__ internals> in broadcast_arrays(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in broadcast_arrays(subok, *args)
536 args = [np.array(_m, copy=False, subok=subok) for _m in args]
537
--> 538 shape = _broadcast_shape(*args)
539
540 if all(array.shape == shape for array in args):
e:\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py in _broadcast_shape(*args)
418 # use the old-iterator because np.nditer does not handle size 0 arrays
419 # consistently
--> 420 b = np.broadcast(*args[:32])
421 # unfortunately, it cannot handle 32 or more arguments directly
422 for pos in range(32, len(args), 31):
ValueError: shape mismatch: objects cannot be broadcast to a single shape
matplotlib v3.3.4
numpy v1.20.1
cv2 v4.0.1
ValueError: shape mismatch
發生是因為image
中的 arrays 尚未正確提取。import matplotlib.pyplot as plt
import numpy as np
# Load the image into an array: image
image = plt.imread('ps09_display-helix.png')
# crop image - required for this image because of wide left/right borders
image = image[100:560, 368:864, :]
# show the cropped image
plt.imshow(image)
# Extract 2-D arrays of the RGB channels: red, green, blue
red, green, blue = image[:,:,0], image[:,:,1], image[:,:,2]
# Flatten the 2-D arrays of the RGB channels into 1-D
red_pixels = red.flatten()
green_pixels = green.flatten()
blue_pixels = blue.flatten()
# Overlay histograms of the pixels of each color in the bottom subplot
plt.figure(figsize=(12, 12))
plt.hist(red_pixels, bins=256, density=False, color='red', alpha=0.5)
plt.hist(green_pixels, bins=256, density=False, color='green', alpha=0.4)
plt.hist(blue_pixels, bins=256, density=False, color='blue', alpha=0.3)
# set labels and ticks
plt.xticks(ticks=np.linspace(0, 1, 17), labels=range(0, 257, 16))
# Cosmetics
plt.title('Histograms from color image')
plt.ylabel('Counts')
plt.xlabel('Intensity')
# Display the plot
plt.show()
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(18, 6))
axes = axes.ravel()
for pix, color, ax in zip([red_pixels, green_pixels, blue_pixels], ['red', 'green', 'blue'], axes):
ax.hist(pix, bins=256, density=False, color=color, alpha=0.5)
# set labels and ticks
ax.set_xticks(ticks=np.linspace(0, 1, 17))
ax.set_xticklabels(labels=range(0, 257, 16), rotation=90)
ax.set_ylim(0, 10000)
# Cosmetics
ax.set_title(f'Histogram from color {color}')
ax.set_ylabel('Counts')
ax.set_xlabel('Intensity')
# Display the plot
plt.tight_layout()
plt.show()
image
上使用cv2.calcHist
中的cv2.calcHist 。import cv2
color = ('r','g','b')
plt.figure(figsize=(8, 6))
for i, col in enumerate(color):
histr = cv2.calcHist([image], [i], None, [256], [0, 1])
plt.plot(histr, color=col)
plt.xlim([0, 256])
plt.xticks(ticks=range(0, 257, 16), labels=range(0, 257, 16))
plt.show()
import numpy as np
red_px = np.histogram(red_pixels, bins=256, range=[0, 1])
green_px = np.histogram(green_pixels, bins=256, range=[0, 1])
blue_px = np.histogram(blue_pixels, bins=256, range=[0, 1])
plt.figure(figsize=(8, 6))
plt.plot(red_px[1][:256], red_px[0], color='r')
plt.plot(green_px[1][:256], green_px[0], color='g')
plt.plot(blue_px[1][:256], blue_px[0], color='b')
plt.xticks(ticks=np.linspace(0, 1, 17), labels=range(0, 257, 16))
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.