【征稿计划第二期】给图像上色,带给你一个精彩世界
让天涯 发布于2019-07 浏览:2123 回复:0
0
收藏
最后编辑于2022-04

【使用攻略】【图像技术】黑白图像上色

一、需求描述

人们的生活越过越丰富多彩。可是家里珍藏已久的旧相册,经过岁月的冲洗边角旮旯儿已泛黄。旧照片是对过往岁月的真实记录,爷爷奶奶年轻时的相貌,衣着、神态,遵循着过去的潮流和规范。去年,百度联合新华社献礼改革开放40周年,发起“给旧时光上色”活动,借助AI的力量,“唤醒”爷爷奶奶手中的黑白老照片,让每个人看到那个年代最真实的景象。

其实,借助百度【黑白图像上色】技术,不仅可以给老照片上色,还能给黑白水墨画等上色,让大家体验一把不一样的水墨画,也是一种新奇的感受。

当然,如果能够给一整篇的【黑白漫画】上色,输出【彩色漫画】,那这个【黑白图像上色】技术在这方面会有很大的作为的,相信会受到很多漫画爱好者的喜爱。

或者可以换个思维,对于【漫画制作】这块,应该是先画出黑白轮廓,然后给图片上色,如果合理利用百度【黑白图像上色】技术,那么在画出黑白轮廓后,参考百度【黑白图像上色】技术处理后的图片,然后再调整颜色的深浅明暗,这样可以大大降低漫画【上色】的工作量,提高漫画【上色】的效率,制作出更加精致的漫画。

另外,像儿童读物等文章都会有【插画】,可以利用【黑白图像上色】技术,给文章的【黑白插画】上色,提供更加好看的【彩色插画】。

二、使用攻略

说明:本文采用C# 语言,开发环境为.Net Core 2.1,采用在线API接口方式实现。
(1)平台接入

登陆 百度智能云-管理中心 创建 “图像处理”应用,获取 “API Key ”和 “Secret Key” :https://console.bce.baidu.com/ai/#/ai/imageprocess/overview/index

(2)接口文档

文档地址:https://ai.baidu.com/docs#/ImageProcessing-API/27271a5c
接口描述:智能识别黑白图像内容并填充色彩,使黑白图像变得鲜活。

请求说明

请求示例

HTTP 方法:POST

请求URL: https://aip.baidubce.com/rest/2.0/image-process/v1/colourize

URL参数:

参数	        值
access_token	通过API Key和Secret Key获取的access_token,参考”Access Token获取”

Header如下:

参数	        值
Content-Type	application/x-www-form-urlencoded

Body中放置请求参数,参数详情如下:

请求参数

参数	是否必选	   类型	    可选值范围	说明
image	  true	  string       -	base64编码后大小不超过4M,最短边至少64px,最长边最大800px,长宽比3:1以内。注意:图片的base64编码是不包含图片头的,如(data:image/jpg;base64,)

返回说明
返回参数

字段	是否必选   类型	     说明
log_id	  是	 uint64	   唯一的log id,用于问题定位
image	  否	 string	   base64编码图片

返回示例

{
"log_id": "6876747463538438254",
"image": "处理后图片的Base64编码"
}

(3)源码共享

3.1-根据 API Key 和 Secret Key 获取 AccessToken

        /// 
        /// 获取百度access_token
        /// 
        /// API Key
        /// Secret Key
        /// 
        public static string GetAccessToken(string clientId, string clientSecret)
        {
            string authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List> paraList = new List>();
            paraList.Add(new KeyValuePair("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair("client_id", clientId));
            paraList.Add(new KeyValuePair("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            string token = jo["access_token"].ToString();
            return token;
        }


3.2-调用API接口获取识别结果
1、在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env) 方法中开启虚拟目录映射功能:

            string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(webRootPath, "Uploads", "BaiduAIs")),
                RequestPath = "/BaiduAIs"
            });


2、 建立Index.cshtml文件

2.1 前台代码:   

    由于html代码无法原生显示,只能简单说明一下:

    主要是一个form表单,需要设置属性enctype="multipart/form-data",否则无法上传图片;

    form表单里面有两个控件:

    一个Input:type="file",asp-for="FileUpload" ,上传图片用;

    一个Input:type="submit",asp-page-handler="Colourize" ,提交并返回识别结果。

    一个img:src="@Model.curPath",显示需要上色的图片。

    一个img:src="@Model.imgProcessPath",显示上色后的图片。

    最后显示后台 msg 字符串列表信息,如果需要输出原始Html代码,则需要使用@Html.Raw()函数。

2.2 后台代码: 

        [BindProperty]
        public IFormFile FileUpload { get; set; }
        private readonly IHostingEnvironment HostingEnvironment;
        public List msg = new List();
        public string curPath { get; set; }
        public string imgProcessPath { get; set; }

        public BodySearchModel(IHostingEnvironment hostingEnvironment)
        {
            HostingEnvironment = hostingEnvironment;
        }

        public async Task OnPostColourizeAsync()
        {
            if (FileUpload is null)
            {
                ModelState.AddModelError(string.Empty, "本地图片!");
            }
            if (!ModelState.IsValid)
            {
                return Page();
            }
            msg = new List();

            string webRootPath = HostingEnvironment.WebRootPath;//wwwroot目录
            string fileDir = Path.Combine(webRootPath, "Uploads//BaiduAIs//");
            string imgName = await UploadFile(FileUpload, fileDir);

            string fileName = Path.Combine(fileDir, imgName);
            string imgBase64 = GetFileBase64(fileName);
            curPath = Path.Combine("/BaiduAIs/", imgName);//需在Startup.cs 文件 的 Configure(IApplicationBuilder app, IHostingEnvironment env)方法中开启虚拟目录映射功能

            string result = GetImageProcessJson(imgBase64, “你的API KEY”, “你的SECRET KEY”);
            JObject jo =(JObject)JsonConvert.DeserializeObject(result);
            try
            {
                string imageProcessBase64 = jo["image"].ToString();
                msg.Add("log_id:" + jo["log_id"].ToString());
                string processImgName = Guid.NewGuid().ToString("N") + ".png";
                string imgSavedPath = Path.Combine(webRootPath, "Uploads//BaiduAIs//", processImgName);
                imgProcessPath = Path.Combine("/BaiduAIs/", processImgName);
                await GetFileFromBase64(imageProcessBase64, imgSavedPath);
            }
            catch(Exception e1)
            {
                msg.Add(result);
            }
            return Page();
        }

        /// 
        /// 上传文件,返回文件名
        /// 
        /// 文件上传控件
        /// 文件绝对路径
        /// 
        public static async Task UploadFile(IFormFile formFile, string fileDir)
        {
            if (!Directory.Exists(fileDir))
            {
                Directory.CreateDirectory(fileDir);
            }
            string extension = Path.GetExtension(formFile.FileName);
            string imgName = Guid.NewGuid().ToString("N") + extension;
            var filePath = Path.Combine(fileDir, imgName);

            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                await formFile.CopyToAsync(fileStream);
            }

            return imgName;
        }
 

        /// 
        /// 返回图片的base64编码
        /// 
        /// 文件绝对路径名称
        /// 
        public static String GetFileBase64(string fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 =  Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }

        /// 
        /// 文件base64解码
        /// 
        /// 文件base64编码
        /// 生成文件路径
        public static async Task GetFileFromBase64(string base64Str, string outPath)
        {
            var contents = Convert.FromBase64String(base64Str);
            using (var fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))
            {
                fs.Write(contents, 0, contents.Length);
                fs.Flush();
            }
        }

        /// 
        /// 图像处理Json字符串
        /// 
        /// 图片base64编码
        /// API Key
        /// Secret Key
        /// 
        public static string GetImageProcessJson(string strbaser64, string clientId, string clientSecret)
        {
            string token = GetAccessToken(clientId, clientSecret);
            string host = "https://aip.baidubce.com/rest/2.0/image-process/v1/colourize?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            string str = "image=" + HttpUtility.UrlEncode(strbaser64);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            return result;
        }


三、效果测试
1、页面:

2、识别结果:

2.1

2.2

2.3

2.4

2.5

四、产品建议

1、试了好几张黑白图片,发现百度的【黑白图片上色】技能给山水、建筑物等实物上色会比较鲜艳,结果也比较满意,而对于纯植物、人物素描等黑白图片则喜欢涂上【红色】,变化不是很大,这方面可能需要再改进一下。

2、如果能够降低对输入图片的大小、长宽的限制,就更好了。

3、如果能给【黑白图像】涂上不同的颜色,然后让用户选择自己喜欢的那张,那就更加好了,毕竟每个人的审美观念不同,喜欢的图片颜色也不一样的。

4、若【黑白图像上色】可以输出多个不同颜色的结果,那么就可以应用到【漫画制作】中去,在漫画完成【线稿】后,可以利用百度【黑白图像上色】技术,提供不用颜色的【上色图】,为漫画【上色】这一步骤提供参考,大大降低【上色】的难度,提高【上色】效率,最终制作出更加精致的【漫画】。

5、可以尝试开发【批量黑白图像】处理功能的应用,比如对一个压缩包、对一个文件夹内的所有图片进行【上色】处理,然后批量输出结果,这样就可以对【黑白漫画】进行【上色】处理,“制作”出【彩色漫画】了。

6、一般像儿童读物等文章都会有【插画】,可以利用【黑白图像上色】技术,给文章的【黑白插画】上色,提供更加好看的【彩色插画】。

 

 

收藏
点赞
0
个赞
TOP
切换版块