pyqt5用Label显示灰度图片的直方图的代码
时间: 2023-04-02 20:00:45 浏览: 185
灰度图像直方图代码
5星 · 资源好评率100%
以下是使用 pyqt5 显示灰度图片的直方图的代码:
```python
import sys
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt5.QtChart import QChart, QChartView, QBarSet, QBarSeries, QValueAxis
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 读取灰度图片
image = QImage('gray_image.png')
image = image.convertToFormat(QImage.Format_Grayscale8)
# 计算直方图
histogram = [] * 256
for y in range(image.height()):
for x in range(image.width()):
pixel_value = image.pixelColor(x, y).red()
histogram[pixel_value] += 1
# 创建柱状图
bar_set = QBarSet('灰度直方图')
for i in range(256):
bar_set.append(histogram[i])
bar_series = QBarSeries()
bar_series.append(bar_set)
chart = QChart()
chart.addSeries(bar_series)
chart.setTitle('灰度直方图')
chart.setAnimationOptions(QChart.SeriesAnimations)
# 设置 X 轴
axis_x = QValueAxis()
axis_x.setRange(, 255)
axis_x.setTickCount(16)
axis_x.setLabelFormat('%d')
chart.addAxis(axis_x, Qt.AlignBottom)
bar_series.attachAxis(axis_x)
# 设置 Y 轴
axis_y = QValueAxis()
axis_y.setRange(, max(histogram))
axis_y.setTickCount(5)
chart.addAxis(axis_y, Qt.AlignLeft)
bar_series.attachAxis(axis_y)
# 显示柱状图
chart_view = QChartView(chart)
chart_view.setRenderHint(QPainter.Antialiasing)
self.setCentralWidget(chart_view)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
希望对你有所帮助!
阅读全文