多线程成功版本

本文介绍了一种利用OpenCV进行图像处理,识别并追踪迷宫路径的方法。通过色彩识别定位迷宫入口与出口,结合深度优先搜索算法,实现路径规划与追踪。使用PyQt5界面展示追踪过程,树莓派版本代码适用于嵌入式设备。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原来是函数名错误

import numpy as np
import sys, time
import cv2  # 导入opencv模块
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread,pyqtSignal

# 迷宫中0的位置代表墙,不能走
# 8代表入口,1代表可走位置
# 888代表出口
migong = '''
0	0	0	0	0	0	0	0	0	0	0	0
0	1	0	1	1	1	1	1	1	1	1	0
0	1	1	1	1	0	1	1	1	1	0	0
0	1	1	1	1	1	1	1	1	888	1	0
0	0	1	0	0	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	0	1	1	1	1	0	0	0	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	8	1	1	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1  	0
0	0	0	0	0	0	0	0	0	0	0	0'''
data = np.array(migong.split(), dtype=int).reshape((12, 12))  # 以空格为分隔符,强制装换成int


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(660, 520)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 640, 480))

        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("../jre/cheku_xinban3333.jpg"))
        self.label.setScaledContents(True)
        self.label.setWordWrap(False)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(150, 450, 31, 31))
        self.label_2.setMinimumSize(QtCore.QSize(0, 0))
        self.label_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("C:/Users/123/.designer/jre/luvse.jpg"))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(32, 24, 30, 30))

        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("../jre/luvse.jpg"))
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))


def yanseshibie():  # 创建一个函数,函数名随意定义
    # 初始化变量
    i = 1
    y0 = 0
    y1 = 49
    x0 = 0
    x1 = 63
    x3 = 1
    y3 = 1
    a = 0
    while (True):

        if i % 10 == 1 and i != 1:  # 下面是下一个的

            y0 = y0 + 49
            y1 = y1 + 49
            x0 = 0
            x1 = 63
            x3 = x3 + 1
            y3 = 1
        if (i >= 101):  # 当i=101代表101次进来,则跳出循环
            break
        frame = cv2.imread("E:/jre/cheku_xinban3333.jpg")  # 读取一张图片
        #   cv2.imshow("original", frame)  # 输出视频每一帧
        frame = frame[y0:y1, x0:x1]  # 裁剪坐标为[y0:y1, x0:x1]#裁减图片
        cv2.imwrite('E:/jre/jrf/' + str(i) + '.jpg', frame)  # 将图片存入这个文件夹

        x0 = x0 + 63  # 像素横坐标每次加63
        x1 = x1 + 63  # 因为是截取图像所以两个都加

        i = i + 1  # 每次进入循环加1

        # 将这一帧图像BGR转换为HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # 这一帧图像限定在HSV蓝色的范围
        blue_lower = np.array([0, 100, 50])
        blue_upper = np.array([10, 255, 225])

        # 阈值HSV图像以仅获得所选颜色,将图像二值化
        # 就是将低于lower_red和高于upper_red的部分分别变成0,lower_red~upper_red之间的值变成255
        blue_mask = cv2.inRange(hsv, blue_lower, blue_upper)

        # Bitwise-AND屏蔽原始图像
        blue_res = cv2.bitwise_and(frame, frame, mask=blue_mask)

        # 结构元素
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

        # 形态学结束
        blue_closing = cv2.morphologyEx(blue_res, cv2.MORPH_CLOSE, kernel)

        # 转换为黑白图像
        blue_gray = cv2.cvtColor(blue_closing, cv2.COLOR_BGR2GRAY)
        (thresh2, blue_bw) = cv2.threshold(blue_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

        # 计算像素变化
        blue_black = cv2.countNonZero(blue_bw)
        print("白色区域:", blue_black)
        if blue_black > 70:
            #  print("视频中有蓝色像素")
            data[x3, y3] = 0

        print(x3, y3)  # 输出每个,x,y的直
        y3 = y3 + 1

        # 显示结果帧
    #  cv2.imshow('blue_quyu', blue_bw)


def direction_set(data):
    """
        函数功能,找到data中未被走过的地方,并同时记录该地方能够走的地方
    """
    dir_set = {}
    v, h = np.where(data > 0)
    for i, j in zip(v, h):
        key = str(i) + str(j)
        if data[i, j + 1] > 0:  # 该地方东邻块是否能走
            dir_set[key] = [str(i) + str(j + 1)]
        if data[i + 1, j] > 0:  # 该地方南邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i + 1) + str(j)]
            else:
                dir_set[key] = [str(i + 1) + str(j)]
        # data[i, j-1]
        if data[i, j - 1] > 0:  # 该地方西邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i) + str(j - 1)]
            else:
                dir_set[key] = [str(i) + str(j - 1)]
        # data[i-1, j]
        if data[i - 1, j] > 0:  # 该地方北邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i - 1) + str(j)]
            else:
                dir_set[key] = [str(i - 1) + str(j)]
    return dir_set


def get_forward_step(exit_index):
    layer_ori = ['92']  # 存放第一层信息
    while True:
        layer_sec = []  # 存放第二层信息
        for key in layer_ori:  # 将layer_ori里面所能达到的位置,存放在layer_sec中
            layer_sec += direction[key]
            if exit_index in direction[key]:
                forward_step = key
        if exit_index in layer_sec: break
        layer_ori = layer_sec
    return forward_step


def zuobiao_zhuanhuan():
    global direction, step
    direction = direction_set(data)

    huish = ['38']
    # data[int(huish[0][0]), int(huish[0][1])] = 888 #将出口用888标记
    while True:
        forward_step = get_forward_step(huish[-1])
        huish += [forward_step]
        if forward_step == '92':
            break
    step = huish[::-1][:-1]
    for ind in step:
        data[int(ind[0]), int(ind[1])] = -8
    # print(data)
    step = np.array(step, dtype=np.int)  # 强制转换成int型
    print(step)
#等待两秒
time.sleep(2)
#创建一个线程类
class MyTemperatureThread(QThread):
    def __init__(self, parent=None):  # 线程初始化
        super().__init__(parent)
    #定义一个信号
    breakSignal = pyqtSignal(int, int)

    # 界面显示,定义x全局变量的时候一认为,先执行界面,所以就没有定义,后来发现,先执行函数再执行界面
    def run(self):
        d = 0
        x2 = 0
        y2 = 0
        while True:
            v = len(step) - 1  # 因为是从0开始的所以-1
            print(v)  # 输出列表长度
            # 将step转换为一串坐标
            y2 = step[d] % 10  #
            x2 = np.array(step[d] / 10, dtype=np.int)
            print(step % 10)  # 输出一连串坐标
            print(np.array(step / 10, dtype=np.int))  # 强制转换成int
            # 坐标转换
            x = 18 + (y2 - 1) * 64
            y = 10 + (x2 - 1) * 48
            self.breakSignal.emit(x,y)
            d = d + 1
            if d > v:
                break
def chuli(a1,b1):

    ui.label_3.move(a1, b1)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    cv2.waitKey(1000)

    yanseshibie()
    zuobiao_zhuanhuan()
    T = MyTemperatureThread()
    T.breakSignal.connect(chuli)
    T.start()
    sys.exit(app.exec_())



修改版,不卡顿版本

import numpy as np
import sys, time
import cv2  # 导入opencv模块
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread,pyqtSignal

# 迷宫中0的位置代表墙,不能走
# 8代表入口,1代表可走位置
# 888代表出口
migong = '''
0	0	0	0	0	0	0	0	0	0	0	0
0	1	0	1	1	1	1	1	1	1	1	0
0	1	1	1	1	0	1	1	1	1	0	0
0	1	1	1	1	1	1	1	1	888	1	0
0	0	1	0	0	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	0	1	1	1	1	0	0	0	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	8	1	1	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1  	0
0	0	0	0	0	0	0	0	0	0	0	0'''
data = np.array(migong.split(), dtype=int).reshape((12, 12))  # 以空格为分隔符,强制装换成int


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(660, 520)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 640, 480))

        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("../jre/cheku_xinban3333.jpg"))
        self.label.setScaledContents(True)
        self.label.setWordWrap(False)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(150, 450, 31, 31))
        self.label_2.setMinimumSize(QtCore.QSize(0, 0))
        self.label_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("C:/Users/123/.designer/jre/luvse.jpg"))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(32, 24, 30, 30))

        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("../jre/luvse.jpg"))
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))


def yanseshibie():  # 创建一个函数,函数名随意定义
    # 初始化变量
    i = 1
    y0 = 0
    y1 = 49
    x0 = 0
    x1 = 63
    x3 = 1
    y3 = 1
    a = 0
    while (True):

        if i % 10 == 1 and i != 1:  # 下面是下一个的

            y0 = y0 + 49
            y1 = y1 + 49
            x0 = 0
            x1 = 63
            x3 = x3 + 1
            y3 = 1
        if (i >= 101):  # 当i=101代表101次进来,则跳出循环
            break
        frame = cv2.imread("E:/jre/cheku_xinban3333.jpg")  # 读取一张图片
        #   cv2.imshow("original", frame)  # 输出视频每一帧
        frame = frame[y0:y1, x0:x1]  # 裁剪坐标为[y0:y1, x0:x1]#裁减图片
        cv2.imwrite('E:/jre/jrf/' + str(i) + '.jpg', frame)  # 将图片存入这个文件夹

        x0 = x0 + 63  # 像素横坐标每次加63
        x1 = x1 + 63  # 因为是截取图像所以两个都加

        i = i + 1  # 每次进入循环加1

        # 将这一帧图像BGR转换为HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # 这一帧图像限定在HSV蓝色的范围
        blue_lower = np.array([0, 100, 50])
        blue_upper = np.array([10, 255, 225])

        # 阈值HSV图像以仅获得所选颜色,将图像二值化
        # 就是将低于lower_red和高于upper_red的部分分别变成0,lower_red~upper_red之间的值变成255
        blue_mask = cv2.inRange(hsv, blue_lower, blue_upper)

        # Bitwise-AND屏蔽原始图像
        blue_res = cv2.bitwise_and(frame, frame, mask=blue_mask)

        # 结构元素
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

        # 形态学结束
        blue_closing = cv2.morphologyEx(blue_res, cv2.MORPH_CLOSE, kernel)

        # 转换为黑白图像
        blue_gray = cv2.cvtColor(blue_closing, cv2.COLOR_BGR2GRAY)
        (thresh2, blue_bw) = cv2.threshold(blue_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

        # 计算像素变化
        blue_black = cv2.countNonZero(blue_bw)
        print("白色区域:", blue_black)
        if blue_black > 70:
            #  print("视频中有蓝色像素")
            data[x3, y3] = 0

        print(x3, y3)  # 输出每个,x,y的直
        y3 = y3 + 1

        # 显示结果帧
    #  cv2.imshow('blue_quyu', blue_bw)


def direction_set(data):
    """
        函数功能,找到data中未被走过的地方,并同时记录该地方能够走的地方
    """
    dir_set = {}
    v, h = np.where(data > 0)
    for i, j in zip(v, h):
        key = str(i) + str(j)
        if data[i, j + 1] > 0:  # 该地方东邻块是否能走
            dir_set[key] = [str(i) + str(j + 1)]
        if data[i + 1, j] > 0:  # 该地方南邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i + 1) + str(j)]
            else:
                dir_set[key] = [str(i + 1) + str(j)]
        # data[i, j-1]
        if data[i, j - 1] > 0:  # 该地方西邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i) + str(j - 1)]
            else:
                dir_set[key] = [str(i) + str(j - 1)]
        # data[i-1, j]
        if data[i - 1, j] > 0:  # 该地方北邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i - 1) + str(j)]
            else:
                dir_set[key] = [str(i - 1) + str(j)]
    return dir_set


def get_forward_step(exit_index):
    layer_ori = ['92']  # 存放第一层信息
    while True:
        layer_sec = []  # 存放第二层信息
        for key in layer_ori:  # 将layer_ori里面所能达到的位置,存放在layer_sec中
            layer_sec += direction[key]
            if exit_index in direction[key]:
                forward_step = key
        if exit_index in layer_sec: break
        layer_ori = layer_sec
    return forward_step


def zuobiao_zhuanhuan():
    global direction, step
    direction = direction_set(data)

    huish = ['38']
    # data[int(huish[0][0]), int(huish[0][1])] = 888 #将出口用888标记
    while True:
        forward_step = get_forward_step(huish[-1])
        huish += [forward_step]
        if forward_step == '92':
            break
    step = huish[::-1][:-1]
    for ind in step:
        data[int(ind[0]), int(ind[1])] = -8
    # print(data)
    step = np.array(step, dtype=np.int)  # 强制转换成int型
    print(step)

#创建一个线程类
class MyTemperatureThread(QThread):
    def __init__(self, parent=None):  # 线程初始化
        super().__init__(parent)
    #定义一个信号
    breakSignal = pyqtSignal(int, int)

    # 界面显示,定义x全局变量的时候一认为,先执行界面,所以就没有定义,后来发现,先执行函数再执行界面
    def run(self):
        d = 0
        x2 = 0
        y2 = 0
        while True:
            v = len(step) - 1  # 因为是从0开始的所以-1
            print(v)  # 输出列表长度
            # 将step转换为一串坐标
            y2 = step[d] % 10  #
            x2 = np.array(step[d] / 10, dtype=np.int)
            print(step % 10)  # 输出一连串坐标
            print(np.array(step / 10, dtype=np.int))  # 强制转换成int
            # 坐标转换
            x = 18 + (y2 - 1) * 64
            y = 10 + (x2 - 1) * 48
            self.breakSignal.emit(x,y)
            time.sleep(1)#原来要在线程里加延时,才可以达到过程效果
            d = d + 1
            if d > v:
                break
def chuli(a1,b1):

    ui.label_3.move(a1, b1)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    cv2.waitKey(1000)

    yanseshibie()
    zuobiao_zhuanhuan()
    T = MyTemperatureThread()
    T.breakSignal.connect(chuli)
    T.start()
    sys.exit(app.exec_())



树莓派版本

import numpy as np
import sys, time
import cv2  # 导入opencv模块
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread,pyqtSignal

# 迷宫中0的位置代表墙,不能走
# 8代表入口,1代表可走位置
# 888代表出口
migong = '''
0	0	0	0	0	0	0	0	0	0	0	0
0	1	0	1	1	1	1	1	1	1	1	0
0	1	1	1	1	0	1	1	1	1	0	0
0	1	1	1	1	1	1	1	1	888	1	0
0	0	1	0	0	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	0	1	1	1	1	0	0	0	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1	0
0	1	8	1	1	1	1	1	1	1	1	0
0	1	1	1	1	1	1	1	1	1	1  	0
0	0	0	0	0	0	0	0	0	0	0	0'''
data = np.array(migong.split(), dtype=int).reshape((12, 12))  # 以空格为分隔符,强制装换成int


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(660, 520)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(0, 0, 640, 480))

        self.label.setText("")
        self.label.setPixmap(QtGui.QPixmap("/home/pi/tupian/cheku_xinban3333.jpg"))
        self.label.setScaledContents(True)
        self.label.setWordWrap(False)
        self.label.setObjectName("label")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(150, 450, 31, 31))
        self.label_2.setMinimumSize(QtCore.QSize(0, 0))
        self.label_2.setMaximumSize(QtCore.QSize(16777215, 16777215))
        self.label_2.setText("")
        self.label_2.setPixmap(QtGui.QPixmap("/home/pi/tupian/luvse.jpg"))
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(82, 394, 30, 30))

        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("/home/pi/tupian/luvse.jpg"))
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))


def yanseshibie():  # 创建一个函数,函数名随意定义
    # 初始化变量
    i = 1
    y0 = 0
    y1 = 49
    x0 = 0
    x1 = 63
    x3 = 1
    y3 = 1
    a = 0
    while (True):

        if i % 10 == 1 and i != 1:  # 下面是下一个的

            y0 = y0 + 49
            y1 = y1 + 49
            x0 = 0
            x1 = 63
            x3 = x3 + 1
            y3 = 1
        if (i >= 101):  # 当i=101代表101次进来,则跳出循环
            break
        frame = cv2.imread("/home/pi/tupian/cheku_xinban3333.jpg")  # 读取一张图片
        #   cv2.imshow("original", frame)  # 输出视频每一帧
        frame = frame[y0:y1, x0:x1]  # 裁剪坐标为[y0:y1, x0:x1]#裁减图片
        cv2.imwrite('/home/pi/migong_tupian/' + str(i) + '.jpg', frame)  # 将图片存入这个文件夹

        x0 = x0 + 63  # 像素横坐标每次加63
        x1 = x1 + 63  # 因为是截取图像所以两个都加

        i = i + 1  # 每次进入循环加1

        # 将这一帧图像BGR转换为HSV
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        # 这一帧图像限定在HSV蓝色的范围
        blue_lower = np.array([0, 100, 50])
        blue_upper = np.array([10, 255, 225])

        # 阈值HSV图像以仅获得所选颜色,将图像二值化
        # 就是将低于lower_red和高于upper_red的部分分别变成0,lower_red~upper_red之间的值变成255
        blue_mask = cv2.inRange(hsv, blue_lower, blue_upper)

        # Bitwise-AND屏蔽原始图像
        blue_res = cv2.bitwise_and(frame, frame, mask=blue_mask)

        # 结构元素
        kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))

        # 形态学结束
        blue_closing = cv2.morphologyEx(blue_res, cv2.MORPH_CLOSE, kernel)

        # 转换为黑白图像
        blue_gray = cv2.cvtColor(blue_closing, cv2.COLOR_BGR2GRAY)
        (thresh2, blue_bw) = cv2.threshold(blue_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

        # 计算像素变化
        blue_black = cv2.countNonZero(blue_bw)
        print("白色区域:", blue_black)
        if blue_black > 70:
            #  print("视频中有蓝色像素")
            data[x3, y3] = 0

        print(x3, y3)  # 输出每个,x,y的直
        y3 = y3 + 1

        # 显示结果帧
    #  cv2.imshow('blue_quyu', blue_bw)


def direction_set(data):
    """
        函数功能,找到data中未被走过的地方,并同时记录该地方能够走的地方
    """
    dir_set = {}
    v, h = np.where(data > 0)
    for i, j in zip(v, h):
        key = str(i) + str(j)
        if data[i, j + 1] > 0:  # 该地方东邻块是否能走
            dir_set[key] = [str(i) + str(j + 1)]
        if data[i + 1, j] > 0:  # 该地方南邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i + 1) + str(j)]
            else:
                dir_set[key] = [str(i + 1) + str(j)]
        # data[i, j-1]
        if data[i, j - 1] > 0:  # 该地方西邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i) + str(j - 1)]
            else:
                dir_set[key] = [str(i) + str(j - 1)]
        # data[i-1, j]
        if data[i - 1, j] > 0:  # 该地方北邻块是否能走
            if key in dir_set:
                dir_set[key] += [str(i - 1) + str(j)]
            else:
                dir_set[key] = [str(i - 1) + str(j)]
    return dir_set


def get_forward_step(exit_index):
    layer_ori = ['92']  # 存放第一层信息
    while True:
        layer_sec = []  # 存放第二层信息
        for key in layer_ori:  # 将layer_ori里面所能达到的位置,存放在layer_sec中
            layer_sec += direction[key]
            if exit_index in direction[key]:
                forward_step = key
        if exit_index in layer_sec: break
        layer_ori = layer_sec
    return forward_step


def zuobiao_zhuanhuan():
    global direction, step
    direction = direction_set(data)

    huish = ['38']
    # data[int(huish[0][0]), int(huish[0][1])] = 888 #将出口用888标记
    while True:
        forward_step = get_forward_step(huish[-1])
        huish += [forward_step]
        if forward_step == '92':
            break
    step = huish[::-1][:-1]
    for ind in step:
        data[int(ind[0]), int(ind[1])] = -8
    # print(data)
    step = np.array(step, dtype=np.int)  # 强制转换成int型
    print(step)

#创建一个线程类
class MyTemperatureThread(QThread):
    def __init__(self, parent=None):  # 线程初始化
        super().__init__(parent)
    #定义一个信号
    breakSignal = pyqtSignal(int, int)

    # 界面显示,定义x全局变量的时候一认为,先执行界面,所以就没有定义,后来发现,先执行函数再执行界面
    def run(self):
        d = 0
        x2 = 0
        y2 = 0
        while True:
            v = len(step) - 1  # 因为是从0开始的所以-1
            print(v)  # 输出列表长度
            # 将step转换为一串坐标
            y2 = step[d] % 10  #
            x2 = np.array(step[d] / 10, dtype=np.int)
            print(step % 10)  # 输出一连串坐标
            print(np.array(step / 10, dtype=np.int))  # 强制转换成int
            # 坐标转换
            x = 18 + (y2 - 1) * 64
            y = 10 + (x2 - 1) * 48
            self.breakSignal.emit(x,y)
            time.sleep(1)#原来要在线程里加延时,才可以达到过程效果
            d = d + 1
            if d > v:
                break
def chuli(a1,b1):

    ui.label_3.move(a1, b1)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    MainWindow = QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    cv2.waitKey(1000)

    yanseshibie()
    zuobiao_zhuanhuan()
    T = MyTemperatureThread()
    T.breakSignal.connect(chuli)
    T.start()
    sys.exit(app.exec_())



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值