image_score.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. from fileinput import filename
  2. import numpy as np
  3. import cv2
  4. # YOLOv5 🚀 by Ultralytics, AGPL-3.0 license
  5. """
  6. Run a Flask REST API exposing one or more YOLOv5s models
  7. """
  8. import requests
  9. import argparse
  10. import io
  11. # import torch
  12. from PIL import Image
  13. from skimage import filters
  14. import os
  15. RESULT_FOLDER = './output_dir/nocutimg' #用于存放检测结果
  16. def draw(img,result,dstDir,filenameList,a):
  17. """
  18. 为待检测图片 绘制矩形框和结果分数
  19. Args:
  20. img (list):利用opesncv按照字节读取的图片
  21. result (list):检测结果的分数列表
  22. dstDir (str):检测结果存放位置(./output_dir/nocutimg/exp_1/xxx.jpg)
  23. filenameList (list):图片名
  24. a:圆盘内接四边形坐标 (左上角,右上角)
  25. return:
  26. """
  27. try:
  28. os.makedirs(dstDir)
  29. except:
  30. pass
  31. for i in range(len(filenameList)):
  32. filename = os.path.join(dstDir,filenameList[i])
  33. cv2.rectangle(img[i], (a[0], a[1]), (a[2], a[3]), (0, 0, 255), 2)
  34. cv2.putText(img[i],"score:{}".format(result[i]), (30, 100),cv2.FONT_HERSHEY_PLAIN,7,(0,0,255),2)
  35. cv2.imwrite(filename,img[i])
  36. print("检查后图片已存入{}".format(dstDir))
  37. def _imageToMatrix(image):
  38. """
  39. 根据名称读取图片对象转化矩阵
  40. :param strName:
  41. :return: 返回矩阵
  42. """
  43. imgMat = np.matrix(image)
  44. return imgMat
  45. def preImgOps(img):
  46. """
  47. 图像的预处理操作
  48. :param img: 图像的而明朝
  49. :return: 灰度化和resize之后的图片对象
  50. """
  51. # 预处理操作
  52. reImg = cv2.resize(img, (300, 400), interpolation=cv2.INTER_CUBIC) #
  53. img2gray = cv2.cvtColor(reImg, cv2.COLOR_BGR2GRAY) # 将图片压缩为单通道的灰度图
  54. return reImg,img2gray
  55. def ReadImage(im_file):
  56. """
  57. 读取图片
  58. :param im_file: 图像的路径
  59. :return: 利用opencv读取的完整图像img 托虫板内接四边形图像cutimg 内接四边形的坐标c[xmin,ymin,xmax,ymax]
  60. """
  61. img = cv2.imdecode(np.fromfile(im_file, dtype=np.uint8), cv2.IMREAD_COLOR)
  62. # imgfile = np.asarray(bytearray(im_file.read()), dtype="uint8")
  63. # img = cv2.imdecode(imgfile, cv2.IMREAD_ANYCOLOR)
  64. ImgShape = img.shape
  65. print("原始图像大小{}".format(ImgShape))
  66. center = [ImgShape[1]/2,ImgShape[0]/2] #圆盘中心
  67. print("图像中心位置{}".format(center))
  68. radius = int(ImgShape[0]/2) #圆盘半径
  69. print("半径{}".format(radius))
  70. length = pow(2,0.5)*radius #圆的内接正方形边长
  71. # print(length)
  72. Size = int(length/2)
  73. xmin = int(center[0] - Size)
  74. xmax = int(center[0] + Size)
  75. ymin = int((center[1] - Size)*1.1)
  76. ymax = int(center[1] + Size)
  77. c = [xmin,ymin,xmax,ymax]
  78. # print(c)
  79. cutimg = img[ymin:ymax,xmin:xmax]
  80. # img = cv2.imdecode(imgfile, cv2.IMREAD_ANYCOLOR)
  81. return img,cutimg,c
  82. def getFileName(imageFile):
  83. url, FileName = os.path.split(imageFile)
  84. # print(FileName)
  85. tamp = []
  86. tamp.append(FileName)
  87. return tamp
  88. #图像清晰度检测
  89. def predict(imageFile):
  90. """
  91. 图像清晰度检测
  92. Args:
  93. imageFile(dir or file):单张图片或者存放图片的文件夹
  94. """
  95. if not os.path.exists(RESULT_FOLDER):
  96. os.makedirs(RESULT_FOLDER)
  97. else:
  98. pass
  99. dirs = os.listdir(RESULT_FOLDER)
  100. print(dirs)
  101. print(imageFile)
  102. # return str(len(dirs))
  103. result = [] #存放清晰度评分
  104. imgList = [] #存放识别后图片
  105. if os.path.isdir(imageFile):
  106. imageFileList = [os.path.join(imageFile,x) for x in os.listdir(imageFile)]
  107. print("imageFileList",imageFileList)
  108. for image in imageFileList:
  109. print(image)
  110. img,cutimg,c = ReadImage(image)
  111. reImg, img2gray= preImgOps(cutimg)
  112. f = _imageToMatrix(img2gray)
  113. tmp = filters.sobel(f)
  114. source=np.sum(tmp**2)
  115. source=np.sqrt(source)
  116. result.append(source)
  117. imgList.append(img)
  118. draw(imgList,result,RESULT_FOLDER+'/exp_'+str(len(dirs)+1)+"/", os.listdir(imageFile),c)
  119. elif os.path.isfile(imageFile):
  120. print("输入文件")
  121. img,cutimg,c = ReadImage(imageFile)
  122. reImg, img2gray= preImgOps(cutimg)
  123. f = _imageToMatrix(img2gray)
  124. tmp = filters.sobel(f)
  125. source=np.sum(tmp**2)
  126. source=np.sqrt(source)
  127. result.append(source)
  128. imgList.append(img)
  129. return result
  130. def main(file_name_is):
  131. """
  132. imageFile 文件夹或者文件
  133. """
  134. # imageFile = "D:\\新建文件夹 (4)\\WeChat Files\\wxid_uqzo45cgfn1j12\\FileStorage\\File\\2023-06\\图片清晰度评分\\861551058842071-20230612141803.jpg"
  135. # imageFile = "C:\\Users\\31453\\Desktop\\云飞代码\\imageQuiltyAssign-toyang\\predict\\861551054010806-20230512095242.jpg"
  136. # imageFile = "https://bigdata-image.oss-cn-hangzhou.aliyuncs.com/Basics/cbd/861551053998357/2023/6/20/192.168.1.108_01_20230620040214180_ALARM_INPUT.jpg?"
  137. # # 把图片下载到本地
  138. # local_dir = "org_image"
  139. # file_name = imageFile.split("/")[-1]
  140. # file_name = file_name.replace("?", "")
  141. # os.makedirs(local_dir) if not os.path.exists(local_dir) else None
  142. # response = requests.get(imageFile)
  143. # with open(os.path.join(local_dir, file_name), 'wb') as f:
  144. # with open(file_name_is, 'wb') as f:
  145. # f.write(response.content)
  146. # result = predict(os.path.join(local_dir, file_name))
  147. # print(result)
  148. result = predict(file_name_is)
  149. print(result)
  150. if __name__ == '__main__':
  151. """
  152. 使用说明:
  153. 修改main()函数中的imageFile:填入待检测图片url or 待检测图片文件夹url
  154. """
  155. fi = "E:\\项目列表\\大数据平台\\打分图片\\3.jpg"
  156. main(fi)