利用OpenCV实现对于两个图像的对比

来源:互联网 发布:帝国cms 今日头条 编辑:程序博客网 时间:2024/06/05 17:28

最近在研究如果将测试结果保存成图片,如何能知道测试是不是通过,其中明显要设计到图像的对比算法。经过了一些研究,最终选择了OpenCV做为实现的基本技术。

OpenCV真的是个强大的东西,相对于Python其他的一些图像库,这个东西更加复杂,也非常灵活,我就直接上代码了


代码有三个部分,一个部分是核心的图像比对,一个是前台的html显示,还有一个就是基于uwsgi的胶水代码

基于Ubuntu 12.04 LTS, python版本2.7


1. 核心图像比对 diff_img.py

import cv2import sysimport numpy as npdef main(img1p,img2p):    img1 = cv2.imread(img1p)    img2 = cv2.imread(img2p)    img3 = img2    height = img1.shape[0]    width = img1.shape[1]    if img1.shape[0] == img2.shape[0] and img1.shape[1] == img2.shape[1]:        diff = False        for i in range (0,width):            for j in range (0,height):                try:                    if color_diff(img1[j,i],img2[j,i]) != True:                        img3[j,i] = [0,0,255]                        diff = True                except:                    pass        if diff:            cv2.imwrite("uploads/wrong.png", img3)            print "yes"        else:            print "no"    else:        print "sizewrong"def color_diff(img1p, img2p):    if len(img1p) != len(img2p):        return False    else:        for i in range(0,len(img1p)):            if img1p[i] != img2p[i]:                return False                break    return Trueif __name__ == '__main__':    if len(sys.argv) > 2 or len(sys.argv) < 1:         main(sys.argv[1],sys.argv[2])


2. 前台HTML显示


<html><title>Test If Images are same</title><body><form id="upload" name="upload" method="POST" action="file_upload.py" enctype="multipart/form-data"><p><h3><font face="arial">Upload Images to See Differences</font></h3></p>        <p>        Base Image: <input type="file" name="file">        </p>        <p>        Test Image: <input type="file" name="file2">        </p><p><input type="submit" value="Upload"></p><p></p><p><h3><font face="arial">Test Result:</font></h3></p><p></p><p><b>%s</b></p><p></p>%s</form>   </body></html>

3.  基于UWSGI的胶水代码 main.py(草稿)

import osimport cgifrom cgi import parse_qs, escapeimport cgitb; cgitb.enable()class upfile(object):    def __init__(self):        self.script_dir = os.path.dirname(__file__)        self.errors = []    def __call__(self, environ, start_response):        f = open(os.path.join(self.script_dir, 'upload2file.html'))        self.output = f.read()        f.close()        self.response_content_type = 'text/html;charset=UTF-8'        fields = None        char_list = None        results = None        if 'POST' == environ['REQUEST_METHOD'] :            fields = cgi.FieldStorage(fp=environ['wsgi.input'],environ=environ, keep_blank_values=1)            base_file = fields['file']            test_file = fields['file2']            fn_b = os.path.basename(base_file.filename)            fn_t = os.path.basename(test_file.filename)            print fn_b,fn_t            open('uploads/' + fn_b, 'wb').write(base_file.file.read())            open('uploads/' + fn_t, 'wb').write(test_file.file.read())            cmd = "python diff_img.py "+"uploads/"+fn_b+" uploads/"+fn_t            results = os.popen(cmd).read()            print "results=",results            if "yes" in results:                result_image = '''                                <table border=\"1\">                                <tr><th>Base Image</th><th>Test Image</th></tr>                                  <tr>                                <td><img src=\"http://siteip/uploads/%s\" /></td>                                <td><img src=\"http://siteip/uploads/wrong.png\" /></td>                                </tr>                                </table>                               '''                result_image = result_image % base_file.filename                self.output = self.output % ("Fail",result_image)            elif "size" in results:                result_image = "<p>"+"<img src=\"http://siteip/uploads/na.png\" />"+"</p>"                self.output = self.output % ("Image sizes are not consistent",result_image)            else:                result_image = "<p>"+"<img src=\"http://siteip/uploads/pass.png\" />"+"</p>"                self.output = self.output % ("Pass",result_image)        else:            result_image = "<p>"+"<img src=\"http://siteip/uploads/na.png\" />"+"</p>"            self.output = self.output % ("N/A",result_image)response_headers = [('Content-type', self.response_content_type),('Content-Length', str(len(self.output)))]        status = '200 OK'        start_response(status, response_headers)        return [self.output]application = upfile()

4. 如何运行?

sudo uwsgi --http :8080 --wsgi-file main.py  --enable-threads

5. 最终效果










0 0
原创粉丝点击