如何使用 Python(或 Perl)检测“暗”图像边框并裁剪到它?

Posted

技术标签:

【中文标题】如何使用 Python(或 Perl)检测“暗”图像边框并裁剪到它?【英文标题】:How can I detect a 'dark' image border and crop to it using Python (or Perl)? 【发布时间】:2020-03-13 12:48:31 【问题描述】:

我有许多从视频中截取的小图像。下面是几个示例图像(存在各种类型的边缘):

简而言之,我正在尝试将图像裁剪到“主”图像的最近部分,该部分位于(几乎)均匀的“黑色”边框内......或者有时,有点“紧张” ' 边缘。你可以把它想象成到图像的中心,然后向外辐射,直到你碰到一个“矩形('黑色'或'接近黑色')边框'。

据我所知,最大的问题是确定图像周围“裁剪矩形”的位置和尺寸。但到目前为止,我还无法做到这一点。

我尝试在 ffmpeg 中使用“cropdetect”过滤器; Perl 没有什么真正有用的东西; ...而且由于我是 Python 新手,我仍然没有弄清楚是否有任何简单的模块可以满足我的需要。我已经看过'scikit-image'......但完全被它迷惑了,因为我对Python没有足够的了解,更不用说图像格式的足够“技术”知识了,颜色深度,操作技术等让我可以使用'scikit-image'。

如果有任何关于如何解决这个问题的建议,我将不胜感激,如果有一种简单的方法可以做到这一点,那就更好了。根据我对“scikit-image”的一点了解,似乎“Canny 边缘检测”或“prewitt_v”/“prewitt_h”过滤器可能是相关的......?

我正在使用 Python 3.7.0(和 Active State Perl v5.20.2,如果有任何使用方法的话),两者都在 Windows 8.1 下运行。

非常感谢您提出的任何建议。

【问题讨论】:

边框是否总是完全相同的颜色?这些文件都是JPEG还是一些PNG?非常暗的窗口标题栏和灰色菜单栏(带有 FileEditView)的高度是否始终相同?跨度> 直接“边框”区域的颜色并不总是“黑色”,但总是比图像的“主体”暗得多......并且在比较捕获时具有不同的厚度。图像始终是 JPEG 文件......但将它们转换为 PNG 格式并没有什么大不了的,如果这意味着它们可以更容易地处理的话。窗口“框架”和下拉菜单的尺寸始终相同...谢谢。 【参考方案1】:

我已经尝试解决这个问题......但它不是很“强大”。当图像被灰度化时,它使用像素的亮度值:-

# ----
#  this will find the 'black'-ish portions and crop the image to these points
#  ozboomer, 25-Apr-2020 3-May-2020
#
# ---------

import pprint
import colorsys

from PIL import Image, ImageFilter

# ---- Define local functions (I *still* don't understand why I have to put these here)

def calculate_luminances(r, g, b):
   """Return luminance values of supplied RGB and greyscale of RGB"""

   lum = (0.2126 * r) + (0.7152 * g) + (0.0722 * b)    # luminance

   H, S, V = colorsys.rgb_to_hsv(r, g, b)              # HSV for the pixel RGB
   R, G, B = colorsys.hsv_to_rgb(H, 0, V)              # ...and greyscale RGB

   glum = (0.2126 * R) + (0.7152 * G) + (0.0722 * B)   # greyscale luminance

   return(lum, glum)

# end calculate_luminances

def radial_edge(radial_vector, ok_range):
   """Return the point in the radial where the luminance marks an 'edge'  """

   print("radial_edge: test range=", ok_range)

   edge_idx = -1
   i = 0

   for glum_value in radial_vector:
      print("  radial_vector: i=", i, "glum_value=", "%.2f" % round(glum_value, 2))

      if int(glum_value) in ok_range:
         print("  IN RANGE!  Return i=", i)
         edge_idx = i
         break

      i = i + 1      
   # endfor         

   return(edge_idx)

# ---- End local function definitions

# ---- Define some constants, variables, etc

#image_file = "cap.bmp"
#image_file = "cap2.png"
#image_file = "cap3.png"
image_file = "Sample.jpg"
#image_file = "cap4.jpg"
output_file = "Cropped.png";

edge_threshold = range(0, 70)  # luminance in this range = 'an edge'

#
# The image layout:-
#
# [0,0]----------+----------[W,0]
#   |            ^            |
#   |            |            |
#   |            R3           |
#   |            |            |
#   +<--- R1 ---[C]--- R2 --->+
#   |            |            |
#   |            R4           |
#   |            |            |
#   |            v            |
# [0,H]----------+----------[W,H]
#

# -------------------------------------
#  Main Routine
#

# ---- Get the image file ready for processing

try:
   im = Image.open(image_file)  # RGB.. mode

except:
   print("Unable to load image,", image_file)
   exit(1)

# Dammit, Perl, etc code is SO much less verbose:-
# open($fh, "<", $filename) || die("\nERROR: Can't open file, '$filename'\n$!\n");

print("Image - Format, size, mode: ", im.format, im.size, im.mode)

W, H = im.size         # The (width x height) of the image
XC = int(W / 2.0)      # Approx. centre of image
YC = int(H / 2.0)

print("Image Centre: (XC,YC)=", XC, ",", YC)

# --- Define the ordinate ranges for each radial

R1_range = range(XC, -1, -1)  # Actual range: XC->0 by -1 ... along YC ordinate
R2_range = range(XC,  W,  1)  #             : XC->W by +1 ... along YC ordinate
R3_range = range(YC, -1, -1)  #             : YC->0 by -1 ... along XC ordinate
R4_range = range(YC,  H,  1)  #             : YC->H by +1 ... along XC ordinate 

# ---- Check each radial for its 'edge' point

radial_luminance = []
for radial_num in range (1,5):  # We'll do the 4 midlines
   radial_luminance.clear()

   if radial_num == 1:
      print("Radial: R1")
      for x in R1_range:
         R, G, B = im.getpixel((x, YC))
         [lum, glum] = calculate_luminances(R, G, B)
         print("  CoOrd=(", x, ",", YC, ") RGB=", 
               (R, G, B), "lum=", "%.2f" % round(lum, 2), 
               "glum=", "%.2f" % round(glum, 2))         
         radial_luminance.append(glum)
      # end: get another radial pixel         

      left_margin = XC - radial_edge(radial_luminance, edge_threshold)

   elif radial_num == 2: 
      print("Radial: R2")
      for x in R2_range:
         R, G, B = im.getpixel((x, YC))
         [lum, glum] = calculate_luminances(R, G, B)
         print("  CoOrd=(", x, ",", YC, ") RGB=", 
               (R, G, B), "lum=", "%.2f" % round(lum, 2), 
               "glum=", "%.2f" % round(glum, 2))         
         radial_luminance.append(glum)  
      # end: get another radial pixel         

      right_margin = XC + radial_edge(radial_luminance, edge_threshold)

   elif radial_num == 3: 
      print("Radial: R3")
      for y in R3_range:
         R, G, B = im.getpixel((XC, y))
         [lum, glum] = calculate_luminances(R, G, B)
         print("  CoOrd=(", XC, ",", y, ") RGB=", 
               (R, G, B), "lum=", "%.2f" % round(lum, 2), 
               "glum=", "%.2f" % round(glum, 2))         
         radial_luminance.append(glum)  
      # end: get another radial pixel         

      top_margin = YC - radial_edge(radial_luminance, edge_threshold)

   elif radial_num == 4: 
      print("Radial: R4")
      for y in R4_range:
         R, G, B = im.getpixel((XC, y))
         [lum, glum] = calculate_luminances(R, G, B)
         print("  CoOrd=(", XC, ",", y, ") RGB=", 
               (R, G, B), "lum=", "%.2f" % round(lum, 2), 
               "glum=", "%.2f" % round(glum, 2))         
         radial_luminance.append(glum)  
      # end: get another radial pixel         

      bottom_margin = YC + radial_edge(radial_luminance, edge_threshold)

   # end: which radial we're processing      

im.close()
crop_items = (left_margin, top_margin, right_margin, bottom_margin)
print("crop_items:", crop_items)

# ---- Crop the original image and save it

im = Image.open(image_file)
im2 = im.crop(crop_items)      
im2.save(output_file, 'png')

exit(0)

# [eof]

我希望 radial_edge() 函数需要修改以检查周围像素以确定我们是否有真正的边缘......'因为可能需要为每个图像确定当前的 ok_range ,因此尝试使用这样的脚本自动进行裁剪是没有意义的。

仍在寻找一种强大而可靠的方法来解决这个问题......

【讨论】:

以上是关于如何使用 Python(或 Perl)检测“暗”图像边框并裁剪到它?的主要内容,如果未能解决你的问题,请参考以下文章

(PHP) 如何检测用户的计算机/浏览器处于暗模式?

如何检测浏览器是不是支持暗模式

如何检测标准输出是不是连接到 Perl 中的 tty?

如何在三星互联网浏览器上检测暗模式?

OpenCV 未知层类型运行暗网检测

如何在浏览器 JavaScript 中检测 OS X 是不是处于暗模式? [复制]