def on_created(self, event):
        if event.is_directory:
            print('不可向图片文件夹中添加此类文件! 即将删除!')
            time.sleep(5)
            help.remove_dir_file(event.src_path)
        else:
            file_name = event.src_path.split('\\')[-1]
            format = file_name.split('.')[-1]
            if format != 'JPG':
                print('请添加格式为JPG的图片,正在删除错误格式图片!')
                time.sleep(5)
                os.remove(event.src_path)
            else:
                data = help.artificial_file_split(event.src_path)
                id = data[0]
                pic_type = data[1]
                pic_size = data[2]

                database = help.openDB()
                conn = database[0]
                cur = database[1]

                cur.execute(
                    "INSERT INTO copy (cultivar_id,pic_type,format,path,pic_size) "
                    "values  (%s,%s,%s,%s,%s)",
                    (id, pic_type, 'JPG', event.src_path, pic_size))
                conn.commit()
                cur.close()
                conn.close
def pro_process(message):
    msg = message.body.decode()
    email = json.loads(msg).get('email', None)
    pathList = json.loads(msg).get('pathList', None)

    # 创建用户目录存放被选中的处理后的图片
    dir = help.read_conf(help.getRoot() +
                         '/config/dataConfig.json')['instrument_compress']
    dir = dir + '\\' + email.split('@')[0]
    print(dir)
    if help.mkdir(dir):
        print("创建" + email + "目录成功!")
    else:
        print("用户目录已存在,清除旧数据")
        help.remove_dir_file(dir)
        help.mkdir(dir)

    database = help.openDB()
    conn = database[0]
    cur = database[1]
    try:
        # 对目标图片进行压缩处理并转换为base64存入数据库
        for path in pathList:
            pic_name = path.split('\\')[-1]
            print(pic_name)
            image = Image.open(path)
            image.thumbnail((600, 400), Image.ANTIALIAS)  # 使用抗锯齿模式生成缩略图(压缩图片)
            image.save(dir + '\\' + pic_name)
            print(pic_name + '  生成缩略图成功')
            with open(dir + '\\' + pic_name, 'rb') as img:
                base64_data = base64.b64encode(img.read())
                print(str(base64_data, 'utf8'))
                base64_data = str(base64_data, 'utf8')
                cur.execute(
                    "update instrument_process_pictures set base64 = %s where path = %s",
                    (
                        base64_data,
                        path,
                    ))
                conn.commit()
        help.save_redis(
            email.split('@')[0] + '_pro_process',
            json.dumps({
                'status': 'success',
                'reason': 'proPic process successfully!'
            }))
    except:
        help.save_redis(
            email.split('@')[0] + '_pro_process',
            json.dumps({
                'status': 'failed',
                'reason': 'pic compress failed!'
            }))

    return True
def save_to_pgs(pathList):
    database = help.openDB()
    conn = database[0]
    cur = database[1]
    for path in pathList:
        data = help.artificial_file_split(path)
        id = data[0]
        pic_type = data[1]
        pic_size = data[2]

        cur.execute(
            "INSERT INTO artificial_shot_pictures (cultivar_id,pic_type,format,path,pic_size) "
            "values  (%s,%s,%s,%s,%s)", (id, pic_type, 'JPG', path, pic_size))
        conn.commit()
    cur.close()
    conn.close
    print('执行完毕')
def ProcessPicToPgs(pathList):
    # 通过help获取数据库连接对象和操作句柄
    database = help.openDB()
    conn = database[0]
    cur = database[1]

    for path in pathList:
        # 获取图片文件名
        picName = path.split('\\')[-1]
        # 使用正则表达式对图片名进行分割
        pattern = r'[-|_|.]'
        result = re.split(pattern, picName)
        angle = result[0]
        cultivar_id = result[1]
        plant_id = result[2]

        # 对日期做出转换
        date = str(result[3][:4]) + '-' + str(result[3][4:6]) + '-' + str(
            result[3][6:9])
        date = datetime.strptime(date, '%Y-%m-%d').date()
        revolution_num = result[4]
        if len(result) == 9:
            process_type = 'LBP'
        else:
            process_type = 'segmentation'
        format = result[-1]
        # 获取文件大小
        pic_size = os.path.getsize(path)
        pic_size = round(pic_size / float(1024 * 1024), 2)

        cur.execute(
            "INSERT INTO instrument_process_pictures (cultivar_id,plant_id,pic_date,revolution_num, angle, process_type,format, path, pic_size) "
            "values  (%s,%s,%s,%s,%s,%s,%s,%s,%s)",
            (cultivar_id, plant_id, date, revolution_num, angle, process_type,
             format, path, pic_size))
        conn.commit()
        print(picName + '入库成功!')
    cur.close()
    conn.close()
def OriginPicToPgs(pathList):
    database = help.openDB()
    conn = database[0]
    cur = database[1]
    for path in pathList:
        # 获取图片的文件名
        picName = path.split('\\')[-1]

        # 利用正则表达式对文件名进行查分
        pattern = r'[-|_|.]'
        result = re.split(pattern, picName)

        # 获取图片的各种属性准备入库
        angle = result[0]
        cultivar_id = result[1]
        plant_id = result[2]

        # 对日期做出转换
        date = str(result[3][:4]) + '-' + str(result[3][4:6]) + '-' + str(
            result[3][6:9])
        date = datetime.strptime(date, '%Y-%m-%d').date()
        revolution_num = result[4]  # 旋转次数
        format = result[-1]
        # 获取文件大小
        pic_size = os.path.getsize(path)
        pic_size = round(pic_size / float(1024 * 1024), 2)

        cur.execute(
            "INSERT INTO instrument_origin_pictures (cultivar_id,plant_id,format,angle,path,revolution_num,pic_date,pic_size) "
            "values  (%s,%s,%s,%s,%s,%s,%s,%s)",
            (cultivar_id, plant_id, format, angle, path, revolution_num, date,
             pic_size))
        conn.commit()
        print(picName + '入库成功!')
    cur.close()
    conn.close()
def pack(message):
    msg = message.body.decode()
    email = json.loads(msg).get('email', None)
    ids = json.loads(msg).get('ids', None)

    if ids:
        database = help.openDB()
        conn = database[0]
        cur = database[1]
        origins = []
        for id in ids:
            cur.execute(
                "select * from instrument_origin_pictures where id = %s",
                (id, ))
            origin = cur.fetchall()
            origins.append(origin[0])

    help.save_redis(
        email.split('@')[0] + '_pack',
        json.dumps({
            'status': 'success',
            'reason': 'instrument data pack finished!'
        }))
    return True
def origin_process(message):
    msg = message.body.decode()
    email = json.loads(msg).get('email', None)
    id = json.loads(msg).get('id', None)

    database = help.openDB()
    conn = database[0]
    cur = database[1]

    if id:
        # 创建用户目录存放被选中的处理后的图片
        dir = help.read_conf(help.getRoot() +
                             '/config/dataConfig.json')['instrument_compress']
        dir = dir + '\\' + email.split('@')[0]
        print(dir)
        if help.mkdir(dir):
            print("创建" + email + "目录成功!")
        else:
            print("用户目录已存在,清除旧数据")
            help.remove_dir_file(dir)
            help.mkdir(dir)

        for i in id:
            cur.execute(
                "select path from instrument_origin_pictures where id = %s",
                (i, ))
            result = cur.fetchall()
            conn.commit()
            if result:
                try:
                    # 读取图片地址
                    path = result[0][0]
                    # 获取图片的名称并将图片的格式转换为jpg方便压缩
                    pic_name = path.split('\\')[-1]
                    pic_name = pic_name.split('.')[0] + '.jpg'
                    image = Image.open(path)  # 将图片读取出来并
                    image.thumbnail((600, 400),
                                    Image.ANTIALIAS)  # 使用抗锯齿模式生成缩略图(压缩图片)
                    image.save(dir + '\\' + pic_name)
                    print(pic_name + '  生成缩略图成功')
                    with open(dir + '\\' + pic_name, 'rb') as img:
                        base64_data = base64.b64encode(img.read())
                        print(str(base64_data, 'utf8'))
                        base64_data = str(base64_data, 'utf8')
                        cur.execute(
                            "update instrument_origin_pictures set base64 = %s where id = %s",
                            (
                                base64_data,
                                i,
                            ))
                        conn.commit()
                except:
                    help.save_redis(
                        'instrument_origin_' + email.split('@')[0],
                        json.dumps({
                            'status': 'failed',
                            'reason': "id为:" + id[i] + "的品种图片处理错误"
                        }))
        help.save_redis(
            'instrument_origin_' + email.split('@')[0],
            json.dumps({
                'status': 'success',
                'reason': 'Origin pictures process succeed!'
            }))
        cur.close()
        conn.close()

    return True
Exemplo n.º 8
0
import base64
import os
import help

database = help.openDB()
conn = database[0]
cur = database[1]

cur.execute(
    "select base64 from pic_18510363933_artificial where cultivar_id = 2 and pic_type = '5'"
)
conn.commit()
result = cur.fetchall()
base64str = result[0][0]
print(base64str)

# with open('G:\\mum_pic\\artificial\\processed\\[email protected]\\2\\2太真图-1.JPG', 'rb') as f:
#     base64str = base64.b64encode(f.read())
#     print(base64str)
#     # base64str += '=' *  missing_padding
#     imgdata = base64.b64decode(base64str)
#     file = open("G:\\1.JPG", 'wb')
#     file.write(imgdata)
#     file.close()
#     print(base64str)

# lens = len(base64str)
# lenx = lens - (lens % 4 if lens % 4 else 4)
# missing_padding = 4 - len(base64str) % 4
# if missing_padding:
#     base64str += '=' *  missing_padding
Exemplo n.º 9
0
def pack(email, classification, cultivar_id, qulity):
    if classification == 'artificial':
        database = help.openDB()
        conn = database[0]
        cur = database[1]

        rootDir = help.read_conf(help.getRoot() +
                                 '/config/dataConfig.json')['user_file']
        path = rootDir + '\\' + email.split('@')[0]
        nowTime = datetime.now().strftime('%Y-%m-%d_')

        # 读取列名
        cur.execute(
            'select column_name from information_schema.columns where table_schema=%s and table_name=%s',
            (
                'public',
                'artificial_character',
            ))
        headers = cur.fetchall()
        header = []
        for i in range(len(headers)):
            header.append(headers[i][0])
        print(header)

        try:
            # 获取用户需要的指标数据,并转换成dataframe格式
            rows = []
            path_list = []
            for i in cultivar_id:
                # 查询特征形状的信息
                cur.execute('select * from artificial_character where id = %s',
                            (i, ))
                row = cur.fetchall()
                rows.append(row[0])
                # 查询指定id 的原图地址
                cur.execute(
                    'select path from artificial_shot_pictures where cultivar_id = %s',
                    (i, ))
                list = cur.fetchall()
                path_list.append(list)

            print(path_list)
            data = pd.DataFrame(rows)

            # 创建文件夹
            if help.mkdir(path):
                print('创建成功目录成功')
            else:
                print('目录已存在,正在清除旧数据')
                help.remove_dir_file(path)
                help.mkdir(path)
            # 将用户需求的数据写入excel中并保存在指定路径
            data.to_excel(path + '\\' + nowTime + '_artificial_characters.xls',
                          header=header,
                          index=False)
            print('保存excel成功')
            for i in range(len(cultivar_id)):
                id = cultivar_id[i]
                help.mkdir(path + '\\' + id)
                for j in range(len(path_list[i])):
                    shutil.copy(path_list[i][j][0], path + '\\' + id)
                    print(path_list[i][j][0])

            # 将当前用户文件夹中的文件打包为压缩文件
            get_file_path = path
            set_file_path = path + '\\' + email.split('@')[0] + '.zip'
            help.compress(get_file_path, set_file_path)
            return set_file_path  # 将打包好的地址返回  方便邮件发送
            print('打包成功')
        except:
            print('打包失败')