我正在尝试将轨迹栏添加到脚本中,该脚本可以查找图像的轮廓,以便仅显示周长比轨迹栏值更长的轮廓。无论我做什么,轮廓都不会改变。
这里是我使用的代码:
import cv2
import numpy as np
# Callback Function for Trackbar (but do not any work)
def nothing(*arg):
pass
def SimpleTrackbar(Image, WindowName):
# Generate trackbar Window Name
TrackbarName = WindowName + "Trackbar"
# Make Window and Trackbar
cv2.namedWindow(WindowName)
cv2.createTrackbar(TrackbarName, WindowName, 0, 255, nothing)
im_gray = cv2.cvtColor(Image, cv2.COLOR_RGB2GRAY)
thresh = cv2.adaptiveThreshold(im_gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 5, 10)
#find contours
_, cnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_LIST , cv2.CHAIN_APPROX_SIMPLE)
# Loop for get trackbar pos and process it
while True:
# Get position in trackbar
TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName)
#draw contours
cntsfiltered = [cnt for cnt in cnts if cv2.arcLength(cnt, True) > TrackbarPos]
cv2.drawContours(Image, cntsfiltered, -1, (0, 255, 0), 1)
# Show in window
cv2.imshow(WindowName, Image)
# If you press "ESC", it will return value
ch = cv2.waitKey(5)
if ch == 27:
break
cv2.destroyAllWindows()
return Image
imager = cv2.imread("tablebasic.jpg")
SimpleTrackbar(imager, "tre")
在while True:
循环中,您正在绘制相同的图像,您需要在此副本上保留原始图像和项目轮廓的单独副本,保持原始图像不变。可以这样做:
while True:
# Get position in trackbar
TrackbarPos = cv2.getTrackbarPos(TrackbarName, WindowName)
# draw contours
img_copy = Image.copy()
cntsfiltered = [cnt for cnt in cnts if cv2.arcLength(cnt, True) > TrackbarPos]
cv2.drawContours(img_copy, cntsfiltered, -1, (0, 255, 0), 1)
# Show in window
cv2.imshow(WindowName, img_copy)
# If you press "ESC", it will return value
ch = cv2.waitKey(5)
if ch == 27:
break
cv2.destroyAllWindows()
return img_copy