def from_pic(self):
        self.thread_run = False
        self.pic_path = askopenfilename(title="选择识别图片", filetypes=[("jpg图片", "*.jpg"), ("png图片", "*.png"),("jpeg图片","*.jpeg")])
        if self.pic_path:
            img_bgr = img_math.img_read(self.pic_path)
            # 图片读取
            first_img, oldimg = self.predictor.img_first_pre(img_bgr)
            # 图片第一次预处理
            self.imgtk = self.get_imgtk(img_bgr)
            # 得到能显示图片
            self.image_ctl.configure(image=self.imgtk)
            #  显示
            th1 = ThreadWithReturnValue(target=self.predictor.img_color_contours, args=(first_img, oldimg))
            th2 = ThreadWithReturnValue(target=self.predictor.img_only_color, args=(oldimg, oldimg, first_img))
            th1.start()
            th2.start()
            r_c, roi_c, color_c = th1.join()
            # 连接成新的字符串
            self.show_roi1(r_c, roi_c, color_c)
            # r_c 车牌 roi_c 车牌图片 color——c 颜色
            print('-----------------------------------------')
            print(r_c,' ',roi_c,' ',color_c)
            r_color, roi_color, color_color = th2.join()
            print(r_color,roi_color,color_color)



            self.show_roi2(r_color, roi_color, color_color)
Exemple #2
0
    def img_mser(self, filename):
        if type(filename) == type(""):
            img = img_math.img_read(filename)
        else:
            img = filename
        oldimg = img
        mser = cv2.MSER_create(_min_area=600)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        regions, boxes = mser.detectRegions(gray)
        colors_img = []
        for box in boxes:
            x, y, w, h = box
            width, height = w, h
            if width < height:
                width, height = height, width
            ration = width / height

            if w * h > 1500 and 3 < ration < 4 and w > h:
                cropimg = img[y:y + h, x:x + w]
                colors_img.append(cropimg)

        debug.img_show(img)
        colors, car_imgs = img_math.img_color(colors_img)
        for i, color in enumerate(colors):
            if color != "no":
                print(color)
                debug.img_show(car_imgs[i])
Exemple #3
0
    def isdark(self, car_pic):

        if type(car_pic) == type(""):
            img = img_math.img_read(car_pic)
        else:
            img = car_pic
        #把图片转换成为灰度图
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        #获取灰度图矩阵的行数和列数
        rows, cols = gray_img.shape[:2]
        dark_sum = 0
        dark_prop = 0
        piexs_sum = rows * cols

        #遍历灰度图的所有像素
        for row in gray_img:
            for col in row:
                if col < 40:
                    dark_sum += 1
        dark_prop = dark_sum / (piexs_sum)
        print("总的黑色像素为" + str(dark_sum))
        print("总像素是:" + str(piexs_sum))
        if dark_prop >= 0.75:
            return True
        return False
Exemple #4
0
    def pic(self, pic_path):
        self.apistr = None
        img_bgr = img_math.img_read(pic_path)
        first_img, oldimg = self.predictor.img_first_pre(img_bgr)
        if not self.cameraflag:
            self.imgtk = self.get_imgtk(img_bgr)
            self.image_ctl.configure(image=self.imgtk)
        th1 = ThreadWithReturnValue(target=self.predictor.img_color_contours,
                                    args=(first_img, oldimg))
        th2 = ThreadWithReturnValue(target=self.predictor.img_only_color,
                                    args=(oldimg, oldimg, first_img))
        th1.start()
        th2.start()
        r_c, roi_c, color_c = th1.join()
        r_color, roi_color, color_color = th2.join()

        self.show_roi2(r_color, roi_color, color_color)
        self.show_roi1(r_c, roi_c, color_c)
        # self.center_window()
        localtime = time.asctime(time.localtime(time.time()))
        if not self.cameraflag:
            if not (r_color or color_color or r_c or color_c):
                self.api_ctl()
            value = [
                localtime, color_c, r_c, color_color, r_color, self.apistr,
                self.pic_source
            ]
            img_excel.excel_add(value)
            img_sql.sql(value[0], value[1], value[2], value[3], value[4],
                        value[5], value[6])
        print(localtime, "|", color_c, r_c, "|", color_color, r_color, "| ",
              self.apistr, "|", self.pic_source)
Exemple #5
0
    def img_first_pre(self, car_pic_file):
        """
        :param car_pic_file: 图像文件
        :return:已经处理好的图像文件 原图像文件
        """
        if type(car_pic_file) == type(""):
            img = img_math.img_read(car_pic_file)
        else:
            img = car_pic_file

        pic_hight, pic_width = img.shape[:2]
        if pic_width > MAX_WIDTH:
            resize_rate = MAX_WIDTH / pic_width
            img = cv2.resize(img, (MAX_WIDTH, int(pic_hight * resize_rate)), interpolation=cv2.INTER_AREA)
        # 缩小图片

        blur = 5
        img = cv2.GaussianBlur(img, (blur, blur), 0)
        oldimg = img
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 转化成灰度图像

        Matrix = np.ones((20, 20), np.uint8)
        img_opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, Matrix)
        img_opening = cv2.addWeighted(img, 1, img_opening, -1, 0)
        # 创建20*20的元素为1的矩阵 开操作,并和img重合

        ret, img_thresh = cv2.threshold(img_opening, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        img_edge = cv2.Canny(img_thresh, 100, 200)
        # Otsu’s二值化 找到图像边缘

        Matrix = np.ones((4, 19), np.uint8)
        img_edge1 = cv2.morphologyEx(img_edge, cv2.MORPH_CLOSE, Matrix)
        img_edge2 = cv2.morphologyEx(img_edge1, cv2.MORPH_OPEN, Matrix)
        return img_edge2, oldimg
 def pic(self, pic_path):
     img_bgr = img_math.img_read(pic_path)
     first_img, oldimg = self.predictor.img_first_pre(img_bgr)
     if not self.cameraflag:
         self.imgtk = self.get_imgtk(img_bgr)
     r_color, roi_color, color_color = self.predictor.img_only_color(
         oldimg, oldimg, first_img)
     print("|", color_color, r_color, "|")
     self.car.append(color_color + ' ' + r_color)
     return color_color, r_color
Exemple #7
0
    def clean(self):
        img_bgr3 = img_math.img_read("pic/hy.png")
        self.imgtk2 = self.get_imgtk(img_bgr3)
        self.image_ctl.configure(image=self.imgtk2)

        self.r_ct2.configure(text="")
        self.color_ct2.configure(text="", state='enable')
        #显示车牌颜色
        self.color_ct2.configure(background='white', text="颜色", state='enable')
        self.pilImage3 = Image.open("pic/locate.png")
        pil_image_resized = self.pilImage3.resize((200, 50), Image.ANTIALIAS)
        self.tkImage3 = ImageTk.PhotoImage(image=pil_image_resized)
        self.roi_ct2.configure(image=self.tkImage3, state='enable')
Exemple #8
0
 def show_img_pre(self):
     if self.thread_run:
         return
     self.thread_run = False
     self.thread_run2 = False
     filename = img_math.img_read("tmp/img_contours.jpg")
     screenwidth = win.winfo_screenwidth()
     screenheight = win.winfo_screenheight()
     win.update()
     width = win.winfo_width()
     height = win.winfo_height()
     laji1 = int((screenwidth - width) / 2)
     laji2 = int((screenheight - height) / 2)
     cv2.imshow("preimg", filename)
     cv2.moveWindow("preimg", laji1 + 100, laji2)
    def videoInsert(self):
        print('调用了')
        capturePath = "E:/成长ing/计算机编程/Github_code/Python_SMP_OPENCV/capture/zz.jpg"
        self.pic_path = capturePath
        print(self.pic_path)
        if self.pic_path:
            img_bgr = img_math.img_read(self.pic_path)
            first_img, oldimg = self.predictor.img_first_pre(img_bgr)
            self.imgtk = self.get_imgtk(img_bgr)
            self.image_ctl.configure(image=self.imgtk)
            th1 = ThreadWithReturnValue(
                target=self.predictor.img_color_contours,
                args=(first_img, oldimg))
            th2 = ThreadWithReturnValue(target=self.predictor.img_only_color,
                                        args=(oldimg, oldimg, first_img))
            th1.start()
            th2.start()
            r_c, roi_c, color_c = th1.join()
            r_color, roi_color, color_color = th2.join()

            print('r_c =', r_c, 'r_color =', r_color, 'r_c Node =',
                  r_c is None)
            # 连接服务器操作
            connection = pymysql.connect(
                host='152.136.105.72',  # 服务器地址
                user='******',  # 数据库账号
                password='******',  # 数据库密码
                db='tcc',  # 使用的是tcc这个表
                charset='utf8mb4')

            try:
                with connection.cursor() as cursor:
                    if (r_c is not None and len(r_c) != 0):

                        # 创建sql语句
                        sql = "insert into `tcc_tbl` (`tcc_title`, `tcc_author`, `tcc_indata`, `flag`) values (%s, %s, %s, %s)"
                        # 执行sql语句

                        inDate = time.localtime(time.time())
                        inDateTime = time.strftime('%Y-%m-%d %H:%M:%S',
                                                   inDate)  # 停车时间
                        cursor.execute(
                            sql, ("".join(r_c), "测试author", inDateTime, "2"))
                        # 提交
                        connection.commit()
                        print('插入成功!', "".join(r_c))
            finally:
                connection.close()
 def from_pic(self):
     self.thread_run = False
     self.pic_path = askopenfilename(title="选择识别图片",
                                     filetypes=[("jpg图片", "*.jpg"),
                                                ("png图片", "*.png")])
     if self.pic_path:
         img_bgr = img_math.img_read(self.pic_path)
         first_img, oldimg = self.predictor.img_first_pre(img_bgr)
         self.imgtk = self.get_imgtk(img_bgr)
         self.image_ctl.configure(image=self.imgtk)
         th1 = ThreadWithReturnValue(
             target=self.predictor.img_color_contours,
             args=(first_img, oldimg))
         th1.start()
         r_c, roi_c, color_c = th1.join()
         self.show_roi1(r_c, roi_c, color_c)
    def from_pic(self):
        self.thread_run = False
        self.pic_path = askopenfilename(title="选择识别图片",
                                        filetypes=[("jpg图片", "*.jpg"),
                                                   ("png图片", "*.png")])

        print('self.pic_path =', self.pic_path)
        if self.pic_path:
            img_bgr = img_math.img_read(self.pic_path)
            first_img, oldimg = self.predictor.img_first_pre(img_bgr)
            self.imgtk = self.get_imgtk(img_bgr)
            self.image_ctl.configure(image=self.imgtk)
            th1 = ThreadWithReturnValue(
                target=self.predictor.img_color_contours,
                args=(first_img, oldimg))
            th2 = ThreadWithReturnValue(target=self.predictor.img_only_color,
                                        args=(oldimg, oldimg, first_img))
            th1.start()
            th2.start()
            r_c, roi_c, color_c = th1.join()
            r_color, roi_color, color_color = th2.join()

            # 连接服务器操作
            connection = pymysql.connect(
                host='152.136.105.72',  # 服务器地址
                user='******',  # 数据库账号
                password='******',  # 数据库密码
                db='tcc',  # 使用的是tcc这个表
                charset='utf8mb4')

            try:
                with connection.cursor() as cursor:
                    # 创建sql语句
                    sql = "insert into `tcc_tbl` (`tcc_title`, `tcc_author`, `tcc_indata`, `flag`) values (%s, %s, %s, %s)"
                    # 执行sql语句
                    tmp = time.localtime(time.time())
                    dateTime = time.strftime('%Y-%m-%d %H:%M:%S', tmp)
                    cursor.execute(sql,
                                   ("".join(r_c), "测试author", dateTime, '2'))
                    # 提交
                    connection.commit()
                    print('插入成功!')
            finally:
                connection.close()
            self.show_roi2(r_color, roi_color, color_color)

            self.show_roi1(r_c, roi_c, color_c)
Exemple #12
0
 def pic(self, pic_path):
     img_bgr = img_math.img_read(pic_path)
     first_img, oldimg = self.predictor.img_first_pre(img_bgr)
     if not self.cameraflag:
         self.imgtk = self.get_imgtk(img_bgr)
         self.image_ctl.configure(image=self.imgtk)
     r_color, roi_color, color_color = self.predictor.img_only_color(
         oldimg, oldimg, first_img)
     self.color_ct2.configure(background=color_color)
     try:
         Plate = HyperLPR_PlateRecogntion(img_bgr)
         r_color = Plate[0][0]
     except:
         pass
     self.show_roi(r_color, roi_color, color_color)
     self.colorimg = color_color
     print("|", color_color, r_color, "|", self.pic_source)
Exemple #13
0
    def img_first_pre(self, car_pic_file):
        """
        :param car_pic_file: 图像文件
        :return:已经处理好的图像文件 原图像文件
        """
        if type(car_pic_file) == type(""):
            img = img_math.img_read(car_pic_file)
        else:
            img = car_pic_file

        pic_hight, pic_width = img.shape[:2]
        if pic_width > MAX_WIDTH:
            resize_rate = MAX_WIDTH / pic_width
            img = cv2.resize(img, (MAX_WIDTH, int(pic_hight * resize_rate)),
                             interpolation=cv2.INTER_AREA)
            # cv_show('缩小的图片', img)

        blur = 3
        img = cv2.GaussianBlur(img, (blur, blur), 0)
        # cv_show('Gauss', img)
        oldimg = img
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # cv_show('BGR2GRAY', img)
        Matrix = np.ones((20, 20), np.uint8)
        # 根据给定类型返回一个矩阵
        img_opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, Matrix)
        # cv_show('open', img_opening)
        img_opening = cv2.addWeighted(img, 1, img_opening, -1, 0)
        # cv_show('重叠', img_opening)
        ret, img_thresh = cv2.threshold(img_opening, 0, 255,
                                        cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        # cv_show("二值化",img_thresh);
        img_edge = cv2.Canny(img_thresh, 100, 200)
        # cv_show('边缘检测', img_edge)
        Matrix = np.ones((4, 19), np.uint8)
        img_edge1 = cv2.morphologyEx(img_edge, cv2.MORPH_CLOSE, Matrix)
        img_edge2 = cv2.morphologyEx(img_edge1, cv2.MORPH_OPEN, Matrix)
        # cv_show('形态学操作', img_edge2)
        return img_edge2, oldimg
Exemple #14
0
    def clean(self):
        if self.thread_run:
            self.cameraflag = 0
            return
        self.thread_run = False
        self.thread_run2 = False
        # self.center_window()
        self.p1.set("")
        img_bgr3 = img_math.img_read("pic/hy.png")
        self.imgtk2 = self.get_imgtk(img_bgr3)
        self.image_ctl.configure(image=self.imgtk2)

        self.r_ctl.configure(text="")
        self.color_ctl.configure(text="", state='enable')

        self.r_ct2.configure(text="")
        self.color_ct2.configure(text="", state='enable')

        self.pilImage3 = Image.open("pic/locate.png")
        w, h = self.pilImage3.size
        pil_image_resized = self.resize(w, h, self.pilImage3)
        self.tkImage3 = ImageTk.PhotoImage(image=pil_image_resized)
        self.roi_ctl.configure(image=self.tkImage3, state='enable')
        self.roi_ct2.configure(image=self.tkImage3, state='enable')
def ysdingwei():
    lable4 = tk.Label(window, text="颜色定位如下", font=('Arial', 15))
    lable4.place(x=750, y=100)
    filename = img_math.img_read(pic_path)
    oldimg = filename
    img_contours = oldimg
    pic_hight, pic_width = img_contours.shape[:2]
    lower_blue = np.array([100, 110, 110])
    upper_blue = np.array([130, 255, 255])
    lower_yellow = np.array([15, 55, 55])
    upper_yellow = np.array([50, 255, 255])
    lower_green = np.array([50, 50, 50])
    upper_green = np.array([100, 255, 255])
    hsv = cv2.cvtColor(filename, cv2.COLOR_BGR2HSV)
    mask_blue = cv2.inRange(hsv, lower_blue, upper_blue)
    mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
    mask_green = cv2.inRange(hsv, lower_yellow, upper_green)
    output = cv2.bitwise_and(hsv, hsv, mask=mask_blue + mask_yellow + mask_green)
    # 根据阈值找到对应颜色
    output = cv2.cvtColor(output, cv2.COLOR_BGR2GRAY)
    Matrix = np.ones((20, 20), np.uint8)
    img_edge1 = cv2.morphologyEx(output, cv2.MORPH_CLOSE, Matrix)
    img_edge2 = cv2.morphologyEx(img_edge1, cv2.MORPH_OPEN, Matrix)
    card_contours = img_math.img_findContours(img_edge2)
    card_imgs = img_math.img_Transform(card_contours, oldimg, pic_width, pic_hight)
    colors, car_imgs = img_math.img_color(card_imgs)
    cv2.imwrite('tmp/chepai_img1.jpg', card_imgs[0])
    print(colors[0])
    img = Image.open("tmp/chepai_img1.jpg")
    photo = ImageTk.PhotoImage(img)
    img = img.resize((160, 40), Image.ANTIALIAS)
    photo = ImageTk.PhotoImage(img)
    label2 = tk.Label(window,anchor="ne")
    label2.config(image=photo)
    label2.image=photo
    label2.place(x=735,y=130)
Exemple #16
0
    def jiazai(self):
        img_1 = img_math.img_read("tmp/img_gray.jpg")
        self.img1 = self.get_imgtk(img_1)
        self.image_1.configure(image=self.img1)

        img_2 = img_math.img_read("tmp/img_edge.jpg")
        self.img2 = self.get_imgtk(img_2)
        self.image_2.configure(image=self.img2)

        img_3 = img_math.img_read("tmp/img_xingtai.jpg")
        self.img3 = self.get_imgtk(img_3)
        self.image_3.configure(image=self.img3)

        img_4 = img_math.img_read("tmp/img_caijian.jpg")
        self.img4 = self.get_imgtk(img_4)
        self.image_4.configure(image=self.img4)

        img_5_1 = img_math.img_read("tmp/chechar1.jpg")
        self.img51 = self.get_imgtk_1(img_5_1)
        self.image_5_1.configure(image=self.img51)

        img_5_2 = img_math.img_read("tmp/chechar2.jpg")
        self.img52 = self.get_imgtk_1(img_5_2)
        self.image_5_2.configure(image=self.img52)

        img_5_3 = img_math.img_read("tmp/chechar3.jpg")
        self.img53 = self.get_imgtk_1(img_5_3)
        self.image_5_3.configure(image=self.img53)

        img_5_4 = img_math.img_read("tmp/chechar4.jpg")
        self.img54 = self.get_imgtk_1(img_5_4)
        self.image_5_4.configure(image=self.img54)

        img_5_5 = img_math.img_read("tmp/chechar5.jpg")
        self.img55 = self.get_imgtk_1(img_5_5)
        self.image_5_5.configure(image=self.img55)

        img_5_6 = img_math.img_read("tmp/chechar6.jpg")
        self.img56 = self.get_imgtk_1(img_5_6)
        self.image_5_6.configure(image=self.img56)

        img_5_7 = img_math.img_read("tmp/chechar7.jpg")
        self.img57 = self.get_imgtk_1(img_5_7)
        self.image_5_7.configure(image=self.img57)
    def insertDate(self):
        file = "C:/Users/fuchen/Desktop/good_park_test"
        for root, dirs, files in os.walk(file):
            print(files)  # 当前路径下所有非目录子文件
            for name in files:
                self.pic_path = file + "/" + name
                print(self.pic_path)
                if self.pic_path:
                    img_bgr = img_math.img_read(self.pic_path)
                    first_img, oldimg = self.predictor.img_first_pre(img_bgr)
                    self.imgtk = self.get_imgtk(img_bgr)
                    self.image_ctl.configure(image=self.imgtk)
                    th1 = ThreadWithReturnValue(
                        target=self.predictor.img_color_contours,
                        args=(first_img, oldimg))
                    th2 = ThreadWithReturnValue(
                        target=self.predictor.img_only_color,
                        args=(oldimg, oldimg, first_img))
                    th1.start()
                    th2.start()
                    r_c, roi_c, color_c = th1.join()
                    r_color, roi_color, color_color = th2.join()

                    print('r_c =', r_c, 'r_color =', r_color, 'r_c Node =',
                          r_c is None)
                    # 连接服务器操作
                    connection = pymysql.connect(
                        host='152.136.105.72',  # 服务器地址
                        user='******',  # 数据库账号
                        password='******',  # 数据库密码
                        db='tcc',  # 使用的是tcc这个表
                        charset='utf8mb4')

                    try:
                        with connection.cursor() as cursor:
                            if (r_c is not None and len(r_c) != 0):

                                # 创建sql语句
                                sql = "insert into `tcc_tbl` (`tcc_title`, `tcc_author`, `tcc_indata`, `tcc_outdata`, `flag`) values (%s, %s, %s, %s, %s)"
                                # 执行sql语句

                                tmp = time.time(
                                ) - random.random() * 60 * 60 * 24 * 30
                                inDate = time.localtime(tmp)
                                outDate = time.localtime(tmp + 60 * 60 * 3)
                                inDateTime = time.strftime(
                                    '%Y-%m-%d %H:%M:%S', inDate)
                                outDateTime = time.strftime(
                                    '%Y-%m-%d %H:%M:%S', outDate)
                                if (random.random() > 0.4):
                                    cursor.execute(
                                        sql, ("".join(r_c), "测试author",
                                              inDateTime, outDateTime, "1"))
                                else:
                                    cursor.execute(sql,
                                                   ("".join(r_c), "测试author",
                                                    inDateTime, "", "2"))
                                # 提交
                                connection.commit()
                                print('插入成功!', "".join(r_c))
                    finally:
                        connection.close()
Exemple #18
0
    def preprocess(self, car_pic_file):
        """
            :param car_pic_file: 图像文件
            :return:已经处理好的图像文件 原图像文件
            """

        if type(car_pic_file) == type(""):
            img = img_math.img_read(car_pic_file)
        else:
            img = car_pic_file

        if img.any() == None:
            return

        pic_hight, pic_width = img.shape[:2]
        print("图片长高为{},图片长为{}".format(pic_hight, pic_width))
        #适当缩小图片
        if pic_width > MAX_WIDTH:  #如果过大了
            resize_rate = MAX_WIDTH / pic_width
            img = cv2.resize(img, (MAX_WIDTH, int(pic_hight * resize_rate)),
                             interpolation=cv2.INTER_AREA)

        #img = cv2.equalizeHist(img)

        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  #转成灰度图
        # cv2.imshow("gray", gray_img)
        # cv2.waitKey(0)

        # dst = cv2.equalizeHist(gray_img)
        # cv2.imshow("dst",dst)
        # cv2.waitKey(0)

        blur_img = cv2.blur(gray_img, (3, 3))  #均值模糊
        #blur_img = cv2.medianBlur(gray_img,3)
        #cv2.imshow("blur",blur_img)
        #cv2.waitKey(0)

        sobel_img = cv2.Sobel(blur_img, cv2.CV_16S, 1, 0,
                              ksize=3)  #sobel获取垂直边缘
        sobel_img = cv2.convertScaleAbs(sobel_img)

        #sobel_img = cv2.Canny(blur_img,100,200)
        cv2.imshow("sobel", sobel_img)
        cv2.waitKey(0)

        hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  #转成HSV

        # cv2.imshow("hsv",hsv_img)
        # cv2.waitKey(0)

        h, s, v = hsv_img[:, :, 0], hsv_img[:, :, 1], hsv_img[:, :, 2]

        #黄色的色调区间再[26,34],蓝色的色调区间再[100,124],绿色的色调区间在[35,100]
        blue_img = (((h > 15) & (h <= 124))) & (s > 70) & (v > 70)  #橙色和紫色
        blue_img = blue_img.astype('float32')

        mix_img = np.multiply(sobel_img, blue_img)
        # cv2.imshow('mix', mix_img)
        # cv2.waitKey(0)

        mix_img = mix_img.astype(np.uint8)

        ret, binary_img = cv2.threshold(mix_img, 0, 255,
                                        cv2.THRESH_BINARY | cv2.THRESH_OTSU)
        # cv2.imshow('binary',binary_img)
        # cv2.waitKey(0)

        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 5))
        close_img = cv2.morphologyEx(binary_img, cv2.MORPH_CLOSE, kernel)

        ##config##
        threshold_m = int(pic_width / 80)  #根据自己调参出来的
        print("开运算的阈值为" + str(threshold_m))
        x = threshold_m
        y = int(threshold_m * 1.3)
        ##config##
        Matrix = np.ones((x, y), np.uint8)
        img_edge1 = cv2.morphologyEx(close_img, cv2.MORPH_CLOSE, Matrix)
        img_edge2 = cv2.morphologyEx(img_edge1, cv2.MORPH_OPEN, Matrix)

        return img_edge2, img
Exemple #19
0
    def img_first_pre(self, car_pic_file):
        """
        :param car_pic_file: 图像文件
        :return:已经处理好的图像文件 原图像文件
        """
        if type(car_pic_file) == type(""):
            img = img_math.img_read(car_pic_file)  #读取文件
        else:
            img = car_pic_file

        pic_hight, pic_width = img.shape[:2]  #取彩色图片的高、宽
        if pic_width > MAX_WIDTH:
            resize_rate = MAX_WIDTH / pic_width
            # 缩小图片
            img = cv2.resize(img, (MAX_WIDTH, int(pic_hight * resize_rate)),
                             interpolation=cv2.INTER_AREA)
        # 关于interpolation 有几个参数可以选择:
        # cv2.INTER_AREA - 局部像素重采样,适合缩小图片。
        # cv2.INTER_CUBIC和 cv2.INTER_LINEAR 更适合放大图像,其中INTER_LINEAR为默认方法。

        img = cv2.GaussianBlur(img, (5, 5), 0)
        # 高斯滤波是一种线性平滑滤波,对于除去高斯噪声有很好的效果
        # 0 是指根据窗口大小( 5,5 )来计算高斯函数标准差

        oldimg = img
        # 转化成灰度图像
        # 转换颜色空间 cv2.cvtColor
        # BGR ---> Gray  cv2.COLOR_BGR2GRAY
        # BGR ---> HSV  cv2.COLOR_BGR2HSV
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        cv2.imwrite("tmp/img_gray.jpg", img)

        #ones()返回一个全1的n维数组
        Matrix = np.ones((20, 20), np.uint8)

        # 开运算:先进性腐蚀再进行膨胀就叫做开运算。它被用来去除噪声。 cv2.MORPH_OPEN
        img_opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, Matrix)

        # 图片叠加与融合
        # g (x) = (1 − α)f0 (x) + αf1 (x)   a→(0,1)不同的a值可以实现不同的效果
        img_opening = cv2.addWeighted(img, 1, img_opening, -1, 0)
        # cv2.imwrite("tmp/img_opening.jpg", img_opening)
        # 创建20*20的元素为1的矩阵 开操作,并和img重合

        # Otsu’s二值化
        ret, img_thresh = cv2.threshold(img_opening, 0, 255,
                                        cv2.THRESH_BINARY + cv2.THRESH_OTSU)
        # Canny 边缘检测
        # 较大的阈值2用于检测图像中明显的边缘  一般情况下检测的效果不会那么完美,边缘检测出来是断断续续的
        # 较小的阈值1用于将这些间断的边缘连接起来
        img_edge = cv2.Canny(img_thresh, 100, 200)
        cv2.imwrite("tmp/img_edge.jpg", img_edge)

        Matrix = np.ones((4, 19), np.uint8)
        # 闭运算:先膨胀再腐蚀
        img_edge1 = cv2.morphologyEx(img_edge, cv2.MORPH_CLOSE, Matrix)
        # 开运算
        img_edge2 = cv2.morphologyEx(img_edge1, cv2.MORPH_OPEN, Matrix)
        cv2.imwrite("tmp/img_xingtai.jpg", img_edge2)
        return img_edge2, oldimg