精易论坛
标题:
python图像二值化
[打印本页]
作者:
哭红眼吓死你
时间:
2025-3-2 11:32
标题:
python图像二值化
import
cv2
import
numpy
as
np
import
tkinter
as
tk
from
PIL
import
Image
,
ImageTk
def
update_mask
(
*
args
):
global
lower_yellow
,
upper_yellow
,
image_hsv
,
image
,
panel
lower_yellow
[
0
]
=
cv2
.
getTrackbarPos
(
'H_min'
,
'Controls'
)
# 获取H_min滑动条的当前位置
lower_yellow
[
1
]
=
cv2
.
getTrackbarPos
(
'S_min'
,
'Controls'
)
# 获取S_min滑动条的当前位置
lower_yellow
[
2
]
=
cv2
.
getTrackbarPos
(
'V_min'
,
'Controls'
)
# 获取V_min滑动条的当前位置
upper_yellow
[
0
]
=
cv2
.
getTrackbarPos
(
'H_max'
,
'Controls'
)
# 获取H_max滑动条的当前位置
upper_yellow
[
1
]
=
cv2
.
getTrackbarPos
(
'S_max'
,
'Controls'
)
# 获取S_max滑动条的当前位置
upper_yellow
[
2
]
=
cv2
.
getTrackbarPos
(
'V_max'
,
'Controls'
)
# 获取V_max滑动条的当前位置
mask
=
cv2
.
inRange
(
image_hsv
,
lower_yellow
,
upper_yellow
)
# 根据HSV值范围创建掩码
result
=
cv2
.
bitwise_and
(
image
,
image
,
mask
=
mask
)
# 应用掩码到原始图像
result_rgb
=
cv2
.
cvtColor
(
result
,
cv2
.
COLOR_BGR2RGB
)
# 将结果图像转换为RGB格式
img
=
Image
.
fromarray
(
result_rgb
)
# 创建PIL图像对象
imgtk
=
ImageTk
.
PhotoImage
(
image
=
img
)
# 创建Tkinter图像对象
panel
.imgtk
=
imgtk
# 保持对图像对象的引用,避免垃圾回收
panel
.
config
(
image
=
imgtk
)
# 更新图像面板显示的图像
# 读取图像(这里输入你的图像名)
image
=
cv2
.
imread
(
'1.jpg'
)
image_hsv
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BGR2HSV
)
# 定义初始的HSV黄色阈值范围
lower_yellow
=
np
.
array
([
20
,
100
,
100
])
upper_yellow
=
np
.
array
([
30
,
255
,
255
])
# 创建Tkinter窗口
root
=
tk
.
Tk
()
root
.
title
(
"颜色阈值化"
)
# 创建一个框架
frame
=
tk
.
Frame
(
root
)
frame
.
pack
()
# 命名窗口
cv2
.
namedWindow
(
'Controls'
)
# 创建滑动条
cv2
.
createTrackbar
(
'H_min'
,
'Controls'
,
lower_yellow
[
0
],
180
,
update_mask
)
cv2
.
createTrackbar
(
'S_min'
,
'Controls'
,
lower_yellow
[
1
],
255
,
update_mask
)
cv2
.
createTrackbar
(
'V_min'
,
'Controls'
,
lower_yellow
[
2
],
255
,
update_mask
)
cv2
.
createTrackbar
(
'H_max'
,
'Controls'
,
upper_yellow
[
0
],
180
,
update_mask
)
cv2
.
createTrackbar
(
'S_max'
,
'Controls'
,
upper_yellow
[
1
],
255
,
update_mask
)
cv2
.
createTrackbar
(
'V_max'
,
'Controls'
,
upper_yellow
[
2
],
255
,
update_mask
)
# 初始化掩码和结果图像
mask
=
cv2
.
inRange
(
image_hsv
,
lower_yellow
,
upper_yellow
)
result
=
cv2
.
bitwise_and
(
image
,
image
,
mask
=
mask
)
# 将结果图像转换为RGB格式以在Tkinter中显示
result_rgb
=
cv2
.
cvtColor
(
result
,
cv2
.
COLOR_BGR2RGB
)
img
=
Image
.
fromarray
(
result_rgb
)
imgtk
=
ImageTk
.
PhotoImage
(
image
=
img
)
# 显示图像
panel
=
tk
.
Label
(
frame
,
image
=
imgtk
)
panel
.
pack
()
# 启动GUI
root
.
mainloop
()
# 等待键盘输入,关闭窗口
cv2
.
waitKey
(
0
)
cv2
.
destroyAllWindows
()
作者:
一指温柔
时间:
2025-3-2 14:18
#在这里快速回复#感谢楼主分享
作者:
ouyasq
时间:
2025-3-2 16:11
支持一下 感谢分享
作者:
何浩文
时间:
2025-3-2 16:53
支持开源~!感谢分享
作者:
year1970
时间:
2025-3-3 08:54
感谢分享
欢迎光临 精易论坛 (https://125.confly.eu.org/)
Powered by Discuz! X3.4