Что нового

Удаление картинок jpg начиная с той, где красное пятно.

Ragn

Новичок
Сообщения
48
Репутация
0
Доброго времени суток. Помогите пожалуйста с вопросом анализа цвета в jpg файлах.
Есть много пронумерованный jpg-файлов.

1-0.jpg
1-1.jpg
1-2.jpg
1-3.jpg
1-4.jpg
1-5.jpg
1-6.jpg
1-7.jpg
1-8.jpg
1-9.jpg
1-10.jpg
1-11.jpg
1-12.jpg

На них нарисованы какие-то знаки.
Но вот на некоторых из них - нарисованы пятна красного цвета (начиная с 1-6.jpg ).
Как с помощью autoit - удалить файлы начиная с того номера, где первый раз встречается красное пятно (не линия) ?

То есть это будут файлы 1-6.jpg, 1-7.jpg, 1-8.jpg, 1-9.jpg, 1-10.jpg, 1-11.jpg, 1-12.jpg
 

Вложения

  • 1.rar
    1.2 МБ · Просмотры: 2

ZaRaki

Знающий
Сообщения
48
Репутация
19
Закидываешь скрипт в папку с изображениями, запускаешь, наслаждаешься.
В приведённом примере формат строго .jpg у файлов, думаю .jpeg и .JPG могут быть неверным форматом.
Цвет указан в $color, в данном случае по примеру приведённый в твоём архиве.
Код ищет прямые линии и фигуры, фигура может быть и кругом и треугольником и прочей фигнёй.
При этом фигура не должна быть менее 40 экранных пикселей что в длину что в высоту.
Конкретно в твоём примере все условия верны - поэтому отрабатывает на ура.
Скрипт будет каждый раз отображать GUI окно с открытой картинкой, не пугайся. Ресайз на нём уже написан, так что размеры и пропорции картинок не важны.
.
Код:
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GDIPlus.au3>
#include <Array.au3>
#include <File.au3>

Global $array[0]
global $FileList=_FileListToArray(@ScriptDir,"*.jpg",1)
global $color = 'ed1b24'

$aa = 1

while $aa < ($FileList[0]+1)
   Example1($FileList)
   $aa = $aa + 1
WEnd

Func Example1($FileList)

      _GDIPlus_Startup()
      $hBitmap = _GDIPlus_BitmapCreateFromFile(@ScriptDir & "\" & $FileList[$aa])
      $img_w = _GDIPlus_ImageGetWidth($hBitmap)
      $img_y = _GDIPlus_ImageGetHeight($hBitmap)
      _GDIPlus_BitmapDispose($hBitmap)
      _GDIPlus_Shutdown()

   $gui_w = @desktopwidth-60
   $gui_y = @DesktopHeight-100
   $normalize_w = $img_w/$gui_w
   $normalize_y = $img_y/$gui_y
   if($img_y/$normalize_w < $gui_y) Then
      $total_w = $gui_w
      $total_y = $img_y/$normalize_w
   Else
      $total_w = $img_w/$normalize_y
      $total_y = $gui_y
   EndIf

   $hgui = GUICreate($FileList[$aa], $gui_w, $gui_y, -1, -1) ; Создаёт окно в центре экрана
   $hImage = GUICtrlCreatePic(@ScriptDir & "\" & $FileList[$aa], 0, 0, $total_w, $total_y)
   GUICtrlSetState(-1, $GUI_DISABLE)
   GUISetState()

WinWaitActive($hgui)
sleep(250)
            $pixel_coords = PixelSearch(0, 0, $gui_w, $gui_y,'0x' & $color,0,5)
            if @error <> 1 Then
               $sosednie_pixel01 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]),6))
               $sosednie_pixel02 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]),6))
               $sosednie_pixel03 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]),6))
               $sosednie_pixel04 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]),6))
               $sosednie_pixel05 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]+5),6))
               $sosednie_pixel06 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]+10),6))
               $sosednie_pixel07 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]-5),6))
               $sosednie_pixel08 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]-10),6))
               $sosednie_pixel09 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]-5),6))
               $sosednie_pixel10 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]-5),6))
               $sosednie_pixel11 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]-5),6))
               $sosednie_pixel12 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]-5),6))
               $sosednie_pixel13 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]-10),6))
               $sosednie_pixel14 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]-10),6))
               $sosednie_pixel15 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]-10),6))
               $sosednie_pixel16 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]-10),6))
               $sosednie_pixel17 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]+5),6))
               $sosednie_pixel18 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]+5),6))
               $sosednie_pixel19 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]+5),6))
               $sosednie_pixel20 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]+5),6))
               $sosednie_pixel21 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]+10),6))
               $sosednie_pixel22 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]+10),6))
               $sosednie_pixel23 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]+10),6))
               $sosednie_pixel24 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]+10),6))

               $search_anotherpixel = _ArrayFindAll($array, $color)

               if ubound($search_anotherpixel)>4 then FileDelete(@ScriptDir & "\" & $FileList[$aa])
            EndIf

   GUIDelete()
EndFunc

Сообщение автоматически объединено:

Если тебе надо чтобы прям все файлы были удалены после того как первый раз встретился файл с красным пятном, то сначала сортировку надо настроить, потому что по смыслу файл 1-11 находится после 1-6, а массив вернёт так, что 1-11 > 1-1 и < 1-2 и не удалит.
Выстраиваешь логические уравнения для сортировки, где пробелы не учитывать вначале/вконце, где сортировку чисел правильно выстраивать (обычно просто умножается на 1), и т.д. Всё это должно быть прям сразу перед первым Global, а после полученного массива $FileList, отсортировать его как тебе надо. А дальше сам доделаешь думаю, foreach->after filedelete
 
Последнее редактирование:
  • Like
Реакции: Ragn
Автор
R

Ragn

Новичок
Сообщения
48
Репутация
0
ZaRaki, спасибо.
Но этот скрипт удалил только те jpg, которые имели это красное пятно.
А я спрашивал - как удалить те jpg, которые идут и после встречи этого пятна.

То есть проверка 1-6.jpg , наличие красного пятна, удаление.
Затем автоматическое удаление (без проверки) - 1-7.jpg ,1-8.jpg ,1-9.jpg ,1-10.jpg ,1-11.jpg ,1-12.jpg - потому что они просто далее по списку идут.
 

ZaRaki

Знающий
Сообщения
48
Репутация
19
ZaRaki, спасибо.
Но этот скрипт удалил только те jpg, которые имели это красное пятно.
А я спрашивал - как удалить те jpg, которые идут и после встречи этого пятна.

То есть проверка 1-6.jpg , наличие красного пятна, удаление.
Затем автоматическое удаление (без проверки) - 1-7.jpg ,1-8.jpg ,1-9.jpg ,1-10.jpg ,1-11.jpg ,1-12.jpg - потому что они просто далее по списку идут.
Именно про это я и говорил. Что нужно делать сортировку полученных названий файлов.
В программировании с этим есть небольшая проблемка, к сожалению autoit тоже обладает этой проблемой.
Видите ли, дело в том, что когда вы смотрите свои файлы с применением сортировки по имени, то список идёт так:
1-0.jpg
1-1.jpg
1-2.jpg
1-3.jpg
и т.д.
А когда autoit получает список файлов, то для него сортировка выглядит вот так:
1-0.jpg
1-1.jpg
1-10.jpg
1-11.jpg
1-12.jpg
1-2.jpg
1-3.jpg
Вот поэтому я и писал что нужно сначала выстроить нормальную сортировку полученного массива наименований файлов. А тут есественно свои трудности.
Я подкорректировал код как надо, но код привязан к жёсткому условию, что все файлы начинаются с цифры 1 и следом дефис/тире
1-
Расчитан что названия будут до 1-9999.jpg
Можно сделать более универсально, но на этот раз вы уж сами доделайте. Пример я вам предоставил как выровнять сортировку.
Код:
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GDIPlus.au3>
#include <Array.au3>
#include <File.au3>

Global $array[0], $newarray[0], $mainindex = 0
global $FileList=_FileListToArray(@ScriptDir,"*.jpg",1)

for $as = 1 to $FileList[0]
   $splnam = stringsplit($FileList[$as],'.')
   $splnam = stringsplit($splnam[1],'-')
   $firstchar = $splnam[1]*1
   $secondchar = $splnam[2]*1

   if(stringlen($secondchar) < 2) Then $secondchar = '0' & $secondchar
   if(stringlen($secondchar) < 3) Then $secondchar = '0' & $secondchar
   if(stringlen($secondchar) < 4) Then $secondchar = '0' & $secondchar
   _arrayadd($newarray,$secondchar)
Next

_arraysort($newarray)

global $color = 'ed1b24'

$aa = 0

while $aa < Ubound($newarray)
   Example1($newarray[$aa]*1)
   $aa = $aa + 1
WEnd

Func Example1($filename)
if $mainindex = 0 Then
      _GDIPlus_Startup()
      $hBitmap = _GDIPlus_BitmapCreateFromFile(@ScriptDir & "\1-" & $filename & ".jpg")
      $img_w = _GDIPlus_ImageGetWidth($hBitmap)
      $img_y = _GDIPlus_ImageGetHeight($hBitmap)
      _GDIPlus_BitmapDispose($hBitmap)
      _GDIPlus_Shutdown()

   $gui_w = @desktopwidth-60
   $gui_y = @DesktopHeight-100
   $normalize_w = $img_w/$gui_w
   $normalize_y = $img_y/$gui_y
   if($img_y/$normalize_w < $gui_y) Then
      $total_w = $gui_w
      $total_y = $img_y/$normalize_w
   Else
      $total_w = $img_w/$normalize_y
      $total_y = $gui_y
   EndIf

   $hgui = GUICreate("1-" & $filename & ".jpg", $gui_w, $gui_y, -1, -1) ; Создаёт окно в центре экрана
   $hImage = GUICtrlCreatePic(@ScriptDir & "\1-" & $filename & ".jpg", 0, 0, $total_w, $total_y)
   GUICtrlSetState(-1, $GUI_DISABLE)
   GUISetState()

WinWaitActive($hgui)
sleep(250)
            $pixel_coords = PixelSearch(0, 0, $gui_w, $gui_y,'0x' & $color,0,5)
            if @error <> 1 Then
               $sosednie_pixel01 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]),6))
               $sosednie_pixel02 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]),6))
               $sosednie_pixel03 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]),6))
               $sosednie_pixel04 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]),6))
               $sosednie_pixel05 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]+5),6))
               $sosednie_pixel06 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]+10),6))
               $sosednie_pixel07 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]-5),6))
               $sosednie_pixel08 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]-10),6))
               $sosednie_pixel09 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]-5),6))
               $sosednie_pixel10 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]-5),6))
               $sosednie_pixel11 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]-5),6))
               $sosednie_pixel12 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]-5),6))
               $sosednie_pixel13 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]-10),6))
               $sosednie_pixel14 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]-10),6))
               $sosednie_pixel15 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]-10),6))
               $sosednie_pixel16 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]-10),6))
               $sosednie_pixel17 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]+5),6))
               $sosednie_pixel18 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]+5),6))
               $sosednie_pixel19 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]+5),6))
               $sosednie_pixel20 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]+5),6))
               $sosednie_pixel21 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]+10),6))
               $sosednie_pixel22 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]+10),6))
               $sosednie_pixel23 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]+10),6))
               $sosednie_pixel24 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]+10),6))

               $search_anotherpixel = _ArrayFindAll($array, $color)

               if ubound($search_anotherpixel)>4 then
                  $mainindex = 1
                  FileDelete(@ScriptDir & "\1-" & $filename & ".jpg")
               EndIf
            EndIf

   GUIDelete()
Else
   FileDelete(@ScriptDir & "\1-" & $filename & ".jpg")
EndIf
EndFunc
 
  • Like
Реакции: Ragn
Автор
R

Ragn

Новичок
Сообщения
48
Репутация
0
ZaRaki
Большое вам спасибо. Теперь заработало.

Только есть единственный вопрос - как эти операции в скрытом режиме проводить ?
(Чтобы не разворачивать всякий раз картинки - на весь экран.)
 

ZaRaki

Знающий
Сообщения
48
Репутация
19
ZaRaki
Большое вам спасибо. Теперь заработало.

Только есть единственный вопрос - как эти операции в скрытом режиме проводить ?
(Чтобы не разворачивать всякий раз картинки - на весь экран.)
Ну только если как-то так.
Само окно вы не увидите, оно ниже за экраном. Но его будет видно в трее и на панели задач.
Можно не показывать в трее, тогда просто допишите Opt("TrayIconHide", 1) так же после инклюдов.
А если и на панели задач хотите убрать, ну тогда окно фокуса постоянно будет маргать с предыдущего приложение, передавать фокус на окно и пропадать, и снова передавать и снова пропадать, пока скрипт не завершится. Меня это напрягает я не стал так делать ))
P.S. Зато видно что скрипт ещё не завершил свою работу если ещё видно иконку.
Код:
#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>
#include <GDIPlus.au3>
#include <Array.au3>
#include <File.au3>

Opt("PixelCoordMode", 2)

Global $array[0], $newarray[0], $mainindex = 0, $parguiwin
global $FileList=_FileListToArray(@ScriptDir,"*.jpg",1)

for $as = 1 to $FileList[0]
   $splnam = stringsplit($FileList[$as],'.')
   $splnam = stringsplit($splnam[1],'-')
   $firstchar = $splnam[1]*1
   $secondchar = $splnam[2]*1

   if(stringlen($secondchar) < 2) Then $secondchar = '0' & $secondchar
   if(stringlen($secondchar) < 3) Then $secondchar = '0' & $secondchar
   if(stringlen($secondchar) < 4) Then $secondchar = '0' & $secondchar
   _arrayadd($newarray,$secondchar)
Next

_arraysort($newarray)

global $color = 'ed1b24'

$aa = 0

$parguiwin = GUICreate("AntiPanel", -1, -1, -1, @DesktopHeight + 200)
GUISetState()
while $aa < Ubound($newarray)
   Example1($newarray[$aa]*1)
   $aa = $aa + 1
WEnd

Func Example1($filename)
if $mainindex = 0 Then
      _GDIPlus_Startup()
      $hBitmap = _GDIPlus_BitmapCreateFromFile(@ScriptDir & "\1-" & $filename & ".jpg")
      $img_w = _GDIPlus_ImageGetWidth($hBitmap)
      $img_y = _GDIPlus_ImageGetHeight($hBitmap)
      _GDIPlus_BitmapDispose($hBitmap)
      _GDIPlus_Shutdown()

   $gui_w = @desktopwidth-60
   $gui_y = @DesktopHeight-100
   $normalize_w = $img_w/$gui_w
   $normalize_y = $img_y/$gui_y
   if($img_y/$normalize_w < $gui_y) Then
      $total_w = $gui_w
      $total_y = $img_y/$normalize_w
   Else
      $total_w = $img_w/$normalize_y
      $total_y = $gui_y
   EndIf

   $hgui = GUICreate("1-" & $filename & ".jpg", $gui_w, $gui_y, -1, @DesktopHeight + 200, -1, -1, $parguiwin)
   $hImage = GUICtrlCreatePic(@ScriptDir & "\1-" & $filename & ".jpg", 0, 0, $total_w, $total_y)
   GUICtrlSetState(-1, $GUI_DISABLE)
   GUISetState()
   WinWaitActive($hgui)
   sleep(250)

            $pixel_coords = PixelSearch(0, 0, $gui_w, $gui_y,'0x' & $color,0,5,$hgui)
            if @error <> 1 Then
               $sosednie_pixel01 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]),6))
               $sosednie_pixel02 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]),6))
               $sosednie_pixel03 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]),6))
               $sosednie_pixel04 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]),6))
               $sosednie_pixel05 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]+5),6))
               $sosednie_pixel06 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]+10),6))
               $sosednie_pixel07 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]-5),6))
               $sosednie_pixel08 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0], $pixel_coords[1]-10),6))
               $sosednie_pixel09 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]-5),6))
               $sosednie_pixel10 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]-5),6))
               $sosednie_pixel11 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]-5),6))
               $sosednie_pixel12 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]-5),6))
               $sosednie_pixel13 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]-10),6))
               $sosednie_pixel14 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]-10),6))
               $sosednie_pixel15 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]-10),6))
               $sosednie_pixel16 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]-10),6))
               $sosednie_pixel17 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]+5),6))
               $sosednie_pixel18 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]+5),6))
               $sosednie_pixel19 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]+5),6))
               $sosednie_pixel20 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]+5),6))
               $sosednie_pixel21 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+5, $pixel_coords[1]+10),6))
               $sosednie_pixel22 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]+10, $pixel_coords[1]+10),6))
               $sosednie_pixel23 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-5, $pixel_coords[1]+10),6))
               $sosednie_pixel24 = _arrayadd($array,hex(PixelGetColor($pixel_coords[0]-10, $pixel_coords[1]+10),6))

               $search_anotherpixel = _ArrayFindAll($array, $color)

               if ubound($search_anotherpixel)>4 then
                  $mainindex = 1
                  FileDelete(@ScriptDir & "\1-" & $filename & ".jpg")
               EndIf
            EndIf

   GUIDelete($hgui)
Else
   FileDelete(@ScriptDir & "\1-" & $filename & ".jpg")
EndIf
EndFunc

GUIDelete($parguiwin)
 
Автор
R

Ragn

Новичок
Сообщения
48
Репутация
0
ZaRaki
Пока что-то не работает.
Действительно появляется иконка на панели задач.
Какое-то время она там висит, а затем исчезает.
Но файлы jpg - остаются в том же составе (то есть удаления не происходит)
 

ZaRaki

Знающий
Сообщения
48
Репутация
19
Ну тогда требуется считывание именно из видимого экрана, то что видно.
Pixelsearch по другому не умеет.
А других способов я не знаю ))
Ну ток разве что постом предыдущим через отображаемое окно )
 

Tempo

AutoIT Гуру
Сообщения
616
Репутация
205
Как вариант, но это довольно медленно
Код:
;~ AutoIt Version: 3.3.14.5
#include <MsgBoxConstants.au3>
#include <File.au3>
#include <GDIPlus.au3>

_Example()

Func _Example()
    Local $aFiles = _FileListToArray(@ScriptDir, "*.jpg", $FLTA_FILES)
    If @error Then Exit MsgBox($MB_TOPMOST + $MB_ICONERROR, Default, "Файлы не найдены")

    Local $aFilesSort[$aFiles[0] + 1][2] = [[$aFiles[0]]]
    For $i = 1 To $aFiles[0]
        $aFilesSort[$i][0] = Number(StringRegExpReplace($aFiles[$i], "[^\d]", ""))
        $aFilesSort[$i][1] = $aFiles[$i]
    Next
    _ArraySort($aFilesSort, 0, 1)

    Local $iIndex = _FilesSearchRect($aFilesSort, 0xFFED1B24, 300, 200, 5)
    If @error Then Exit MsgBox($MB_TOPMOST + $MB_ICONERROR, Default, "Пятно не найдено")

    For $i = $iIndex + 1 To $aFilesSort[0][0]
;~         FileDelete($aFilesSort[$i][1])
        FileRecycle($aFilesSort[$i][1])
    Next
EndFunc   ;==>_Example

Func _FilesSearchRect(Const ByRef $aFilesSort, $iColor, $iRectW, $iRectH, $iStep = 1)
    Local $hBitmap, $iW, $iH, $tBitmapData, $iScan0, $tPixel, $iPixel, $iRowOffset
    Local $iSearchRectW, $iSearchRectH, $iSearchRectRowOffset, $iRet = -1
    _GDIPlus_Startup()
    For $i = 1 To $aFilesSort[0][0]
        $hBitmap = _GDIPlus_BitmapCreateFromFile($aFilesSort[$i][1])
        $iW = _GDIPlus_ImageGetWidth($hBitmap)
        $iH = _GDIPlus_ImageGetHeight($hBitmap)

        $tBitmapData = _GDIPlus_BitmapLockBits($hBitmap, 0, 0, $iW, $iH, $GDIP_ILMREAD, $GDIP_PXF32ARGB)
        $iScan0 = DllStructGetData($tBitmapData, "Scan0")
        $tPixel = DllStructCreate("int[" & $iW * $iH & "]", $iScan0)
        For $iY = 0 To $iH - $iRectH - 1 Step $iStep
            $iRowOffset = $iY * $iW + 1
            For $iX = 0 To $iW - $iRectW - 1 Step $iStep
                $iPixel = DllStructGetData($tPixel, 1, $iRowOffset + $iX)
                If $iPixel = $iColor Then
                    $iSearchRectW = $iX + $iRectW
                    $iSearchRectH = $iY + $iRectH
                    For $iRectY = $iY To $iSearchRectH Step $iStep
                        $iSearchRectRowOffset = $iRectY * $iW + 1
                        For $iRectX = $iX To $iSearchRectW Step $iStep
                            $iPixel = DllStructGetData($tPixel, 1, $iSearchRectRowOffset + $iRectX)
                            If $iPixel <> $iColor Then
                                $iX += $iSearchRectW - $iRectX
                                ContinueLoop 3
                            EndIf
                        Next
                    Next
                    $iRet = $i
                    ExitLoop 2
                EndIf
            Next
        Next
        _GDIPlus_BitmapUnlockBits($hBitmap, $tBitmapData)
        _GDIPlus_BitmapDispose($hBitmap)
        If $iRet <> -1 Then ExitLoop
    Next
    _GDIPlus_Shutdown()
    Return SetError($iRet = -1, 0, $iRet)
EndFunc   ;==>_FilesSearchRect
 
  • Like
Реакции: Ragn
Верх