Форум программистов, компьютерный форум, киберфорум
Visual Basic
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.85/13: Рейтинг темы: голосов - 13, средняя оценка - 4.85
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69

how can fast find small picture in screen

20.05.2021, 02:36. Показов 2610. Ответов 14
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Dear friend, I have a question, how can I quickly find the location of a picture in a big picture? Is there a good algorithm? Maybe there is also the problem of chromatic aberration. This is a subject of image recognition!
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
20.05.2021, 02:36
Ответы с готовыми решениями:

Создать объект типа Picture с использованием картинки из ресурсов / преобразовать тип Image к Picture
Здравствуйте. Нашел пост о том, как добавлять картинки в ресурсы программы,но не смог разобраться в том, как создавать объекты типа Picture...

Screen.width и screen.height в Firemonkey desktop aplication
Проблема в том что я не могу написать код screen.width и screen.height в Firemonkey desktop aplication. Где то читал что нужно прописать в...

Видеоплеер с функцией Picture in Picture
Привет! Знает кто-нибудь, есть ли какой-нибудь видеоплеер для джумлы 3, который может показывать одновременно 2 видео как PIP? или можно...

14
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
10.06.2021, 05:52  [ТС]
Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
Option Explicit
 
Private Declare Function GetDIBits _
                Lib "gdi32" (ByVal aHDC As Long, _
                             ByVal hBitmap As Long, _
                             ByVal nStartScan As Long, _
                             ByVal nNumScans As Long, _
                             lpBits As Any, _
                             lpBI As BITMAPINFO, _
                             ByVal wUsage As Long) As Long
Private Declare Function SetDIBits _
                Lib "gdi32" (ByVal hDC As Long, _
                             ByVal hBitmap As Long, _
                             ByVal nStartScan As Long, _
                             ByVal nNumScans As Long, _
                             lpBits As Any, _
                             lpBI As BITMAPINFO, _
                             ByVal wUsage As Long) As Long
 
'颜色表
Private Type RGBQUAD
    rgbBlue As Byte
    rgbGreen As Byte
    rgbRed As Byte
    rgbAlpha As Byte   '透明通道
End Type
 
Private Type BITMAPINFOHEADER
    biSize As Long          '位图大小
    biWidth As Long
    biHeight As Long
    biPlanes As Integer
    biBitCount As Integer   '信息头长度
    biCompression As Long   '压缩方式
    biSizeImage As Long
    biXPelsPerMeter As Long
    biYPelsPerMeter As Long
    biClrUsed As Long
    biClrImportant As Long
End Type
 
Private Type BITMAPINFO
    bmiHeader As BITMAPINFOHEADER
    bmiColors As RGBQUAD
End Type
 
Public Type mRect
    Top  As Long
  
    Left As Long
    
    w As Long
    h As Long
End Type
 
Public Type mOffset
    X  As Long
  
    Y As Long
 
End Type
 
'图片文件头
Dim BI  As BITMAPINFO
Dim BI1 As BITMAPINFO
 
 
'在图片1中查找图片2,是否找出全部
Public Function FindPic(P1 As VB.PictureBox, P2 As VB.PictureBox, Offset As mOffset, Optional ColorDeviation As Byte = 100, Optional Similarity As Single = 0.9, Optional FindAll As Boolean = False) As Boolean
    Dim mSimilarity As Long
    
    Dim w      As Long, h As Long, i As Long, J As Long
    Dim W2     As Long, H2 As Long, I2 As Long, J2 As Long
 
    Dim zPic() As Byte, fPic() As Byte
    Dim R      As Byte, G As Byte, B As Byte
 
    '1 获得图片2数据
    W2 = frmain.ScaleX(P2.Picture.Width, vbHimetric, vbPixels)
    H2 = frmain.ScaleY(P2.Picture.height, 8, 3)
 
    With BI.bmiHeader
        .biSize = Len(BI.bmiHeader)
        .biWidth = W2
        .biHeight = -H2
        .biBitCount = 32
        .biPlanes = 1
    End With
 
    ReDim zPic(3, W2 - 1, H2 - 1)
 
    i = GetDIBits(P2.hDC, P2.Picture.Handle, 0, H2, zPic(0, 0, 0), BI, 0)
    'Debug.Print I
    '如果在这里处理一下,图像大的话,可能会快一点。
 
    '2 获得图片1数据
    w = frmain.ScaleX(P1.Picture.Width, vbHimetric, vbPixels)
    h = frmain.ScaleY(P1.Picture.height, 8, 3)
 
    With BI1.bmiHeader
        .biSize = Len(BI1.bmiHeader)
        .biWidth = w
        .biHeight = -h
        .biBitCount = 32
        .biPlanes = 1
    End With
 
    '    frmain.fdpic.height = P2.height
    '    frmain.fdpic.width = P2.width
    '    frmain.fdpic.ScaleMode = vbPixels
 
    '    For J2 = 0 To H2 - 2 '循环判断小图片
    '        For I2 = 0 To W2 - 2
    '            frmain.fdpic.PSet (I2, J2), rgb(zPic(2, I2, J2), zPic(1, I2, J2), zPic(0, I2, J2))
    '            VBA.DoEvents
    '        Next I2
    '    Next J2
    '
    '    frmain.fdpic.Refresh
 
    ReDim fPic(3, w - 1, h - 1)
    i = GetDIBits(P1.hDC, P1.Picture.Handle, 0, h, fPic(0, 0, 0), BI1, 0)
    'Debug.Print I
 
    '分析查找
    For J = 0 To h - H2 - 1
        For i = 0 To w - W2 - 1
            VBA.DoEvents
 
            For J2 = 0 To H2 - 2 '循环判断小图片
                For I2 = 0 To W2 - 2
                
                    'If zPic(2, I2, J2) + 50 < fPic(2, I + I2, J + J2) Or fPic(2, I + I2, J + J2) < zPic(2, I2, J2) Then GoTo ExitLine: 'R
                    ' If zPic(1, I2, J2) + 50 < fPic(1, I + I2, J + J2) Or fPic(1, I + I2, J + J2) < zPic(1, I2, J2) Then GoTo ExitLine: 'G
                    ' If zPic(0, I2, J2) + 50 < fPic(0, I + I2, J + J2) Or fPic(0, I + I2, J + J2) < zPic(0, I2, J2) Then GoTo ExitLine: 'B
                    If Abs(CInt(zPic(2, I2, J2)) - CInt(fPic(2, i + I2, J + J2))) > ColorDeviation Then
                        GoTo ExitLine:  'R
                    End If
 
                    If Abs(CInt(zPic(1, I2, J2)) - CInt(fPic(1, i + I2, J + J2))) > ColorDeviation Then
                        GoTo ExitLine: 'G'
                    End If
 
                    If Abs(CInt(zPic(0, I2, J2)) - CInt(fPic(0, i + I2, J + J2))) > ColorDeviation Then
                        GoTo ExitLine: 'B
                    End If
 
                    mSimilarity = mSimilarity + 1
 
                    If mSimilarity / (H2 * W2) >= Similarity Then
                      GoTo Ok:
                    End If
                
                Next I2
            Next J2
Ok:
            Debug.Print "FIND:", W2, H2
 
            Offset.X = i
            Offset.Y = J
            
            FindPic = True
            'Load frmain.Shape1(frmain.Shape1.Count)
        
'            With frmain.Shape1
'                .Move i, J, W2, H2
'                .BorderWidth = 2
'                .Visible = True
'            End With
 
            Exit Function
ExitLine:
           mSimilarity = 0
        Next i
    Next J
 
    'MsgBox "FIND" & frmain.Shape1.Count - 1 & "SAME。"
End Function
 
'Private Sub Cmd1_Click()
'    Dim Ps() As Integer     '找到图片的位置数组
'    Ps = FindPic(Pic1, Pic2)
'
'End Sub
 
'Private Sub Form_Load()
'
'    With Shape1(0)
'        .height = Pic2.height
'        .width = Pic2.width
'    End With
'
'End Sub
0
39 / 39 / 8
Регистрация: 15.08.2014
Сообщений: 634
10.06.2021, 11:41
o Yes!)))
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
27.06.2021, 09:22  [ТС]
No one has better advice?

Добавлено через 1 час 13 минут
Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
Public Sub TemplateMatchDib(Lwidth As Long, Lheight As Long, Temph As Long, Tempw As Long)
Dim i As Integer, j As Integer, m As Integer, n As Integer
Dim dsigmast As Double, dsigmas As Double, dsigmat As Double, r As Double
Dim LmaxWidth As Long, LmaxHeight As Long
Dim MidMatrix() As Long
ReDim MidMatrix(3, Lwidth, Lheight) As Long
 
On Error Resume Next
For i = 1 To Lwidth
For j = 1 To Lheight
For m = 1 To 3 '处理的是24位位图,可选择处理灰度图,速度会快一些
MidMatrix(m, i, j) = 255 '初始化中间矩阵
Next m
Next j
Next i
dsigmat = 0
For n = 1 To Temph - 1
For m = 1 To Tempw - 1
dsigmat = dsigmat + Val(bDATA(1, m, n)) ^ 2 '计算dsigmat
Next m
Next n
maxr = 0
For j = 1 To Lheight - Temph + 1 Step 3 '找到图象中最大相似性出现的位置
For i = 1 To Lwidth - Tempw + 1 Step 3 '此初的step改为1似乎对结果没什么影响,为3可提高速度
dsigmast = 0
dsigmas = 0 '归0
For n = 1 To Temph
For m = 1 To Tempw
dsigmas = dsigmas + (Val(iDATA(1, i + m - 1, j + n - 1)) + Val(iDATA(2, i + m - 1, j + n - 1)) + Val(iDATA(3, i + m - 1, j + n - 1)) / 3) ^ 2
dsigmast = dsigmast + (Val(iDATA(1, i + m - 1, j + n - 1)) + Val(iDATA(2, i + m - 1, j + n - 1)) + Val(iDATA(3, i + m - 1, j + n - 1)) / 3) * (Val(bDATA(1, m, n)) + Val(bDATA(1, m, n)) + Val(bDATA(1, m, n))) / 3
Next m
Next n
r = dsigmast / (Sqr(dsigmas) * Sqr(dsigmat)) '计算相似性
If r > maxr Then '与最大相似性比较
maxr = r
LmaxWidth = i
LmaxHeight = j
End If
Next i
Next j
the code is too slow
0
 Аватар для Argus19
1427 / 444 / 78
Регистрация: 24.09.2017
Сообщений: 2,527
Записей в блоге: 22
27.06.2021, 10:50
Not very clear what is the search criterion for a small picture?
0
 Аватар для Pro_grammer
6807 / 2839 / 527
Регистрация: 24.04.2011
Сообщений: 5,308
Записей в блоге: 10
27.06.2021, 11:08
Argus19, к примеру у тебя есть скриншот игры, и есть образец изображения предмета, который надо собрать. Он всегда одинаковый, но расположение разное.
Как быстро найти координаты всех предметов на изображении?



Это может быть любое изображение, кнопка например или враг. Суть в том, что ты знаешь, какое изображение нужно искать, но не знаешь в каком месте оно появится, тем более оно может двигаться, а потому нужен очень быстрый поиск.
0
 Аватар для Argus19
1427 / 444 / 78
Регистрация: 24.09.2017
Сообщений: 2,527
Записей в блоге: 22
27.06.2021, 11:45
Цитата Сообщение от Pro_grammer Посмотреть сообщение
Это может быть любое изображение
Т.е. поиск по шаблону?
0
Модератор
10057 / 3902 / 884
Регистрация: 22.02.2013
Сообщений: 5,853
Записей в блоге: 79
28.06.2021, 01:43
Лучший ответ Сообщение было отмечено xxdoc как решение

Решение

Compile it with all the optimizations.
Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
Option Explicit
 
Private Type tPoint
    lX      As Long
    lY      As Long
End Type
 
Private Type tImageDesc ' // 32bpp only
    lWidth  As Long
    lHeight As Long
    bData() As Byte
End Type
 
Private Type RGBQUAD
    rgbBlue         As Byte
    rgbGreen        As Byte
    rgbRed          As Byte
    rgbReserved     As Byte
End Type
 
Private Type BITMAPINFOHEADER
    biSize          As Long
    biWidth         As Long
    biHeight        As Long
    biPlanes        As Integer
    biBitCount      As Integer
    biCompression   As Long
    biSizeImage     As Long
    biXPelsPerMeter As Long
    biYPelsPerMeter As Long
    biClrUsed       As Long
    biClrImportant  As Long
End Type
 
Private Type BITMAPINFO
    bmiHeader       As BITMAPINFOHEADER
    bmiColors       As RGBQUAD
End Type
 
Private Type SAFEARRAY1D
    cDims           As Integer
    fFeatures       As Integer
    cbElements      As Long
    cLocks          As Long
    pvData          As Long
    cElements       As Long
    lLbound         As Long
End Type
 
Private Declare Function GetDIBits Lib "gdi32" ( _
                         ByVal aHDC As Long, _
                         ByVal hBitmap As Long, _
                         ByVal nStartScan As Long, _
                         ByVal nNumScans As Long, _
                         ByRef lpBits As Any, _
                         ByRef lpBI As BITMAPINFO, _
                         ByVal wUsage As Long) As Long
Private Declare Function CreateDIBSection Lib "gdi32" ( _
                         ByVal hDC As Long, _
                         ByRef pBitmapInfo As BITMAPINFO, _
                         ByVal un As Long, _
                         ByRef lplpVoid As Long, _
                         ByVal handle As Long, _
                         ByVal dw As Long) As Long
Private Declare Function CreateCompatibleDC Lib "gdi32" ( _
                         ByVal hDC As Long) As Long
Private Declare Function SaveDC Lib "gdi32" ( _
                         ByVal hDC As Long) As Long
Private Declare Function RestoreDC Lib "gdi32" ( _
                         ByVal hDC As Long, _
                         ByVal nSavedDC As Long) As Long
Private Declare Function DeleteDC Lib "gdi32" ( _
                         ByVal hDC As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" ( _
                         ByVal hObject As Long) As Long
Private Declare Function SelectObject Lib "gdi32" ( _
                         ByVal hDC As Long, _
                         ByVal hObject As Long) As Long
Private Declare Function GetDC Lib "user32" ( _
                         ByVal hWnd As Long) As Long
Private Declare Function ReleaseDC Lib "user32" ( _
                         ByVal hWnd As Long, _
                         ByVal hDC As Long) As Long
Private Declare Function BitBlt Lib "gdi32" ( _
                         ByVal hDestDC As Long, _
                         ByVal x As Long, _
                         ByVal y As Long, _
                         ByVal nWidth As Long, _
                         ByVal nHeight As Long, _
                         ByVal hSrcDC As Long, _
                         ByVal xSrc As Long, _
                         ByVal ySrc As Long, _
                         ByVal dwRop As Long) As Long
Private Declare Sub MoveArray Lib "msvbvm60" _
                    Alias "__vbaAryMove" ( _
                    ByRef Destination() As Any, _
                    ByRef Source As Any)
 
Private m_tTemplate     As tImageDesc
Private m_tMask         As tImageDesc
Private m_tScreen       As tImageDesc
Private m_hBuffer       As Long
Private m_hBufDC        As Long
Private m_tSaDesc       As SAFEARRAY1D
Private m_pSADesc       As Long
Private m_lFPS          As Long
Private m_bUnloading    As Boolean
Private m_bIsRunning    As Boolean
 
Private Sub Form_Load()
    
    InitializeScreenBuffer
    m_tTemplate = ImageDescFromFile(App.Path & "\template.bmp")
    m_tMask = ImageDescFromFile(App.Path & "\mask.bmp")
 
End Sub
 
Private Sub cmdStart_Click()
    
    If m_bIsRunning Then
        m_bIsRunning = False
        Exit Sub
    End If
    
    tmrFPS.Enabled = True
    cmdStart.Caption = "Stop"
    m_bIsRunning = True
    
    Do While m_bIsRunning
    
        FindTemplate
        m_lFPS = m_lFPS + 1
        DoEvents
        
    Loop
    
    If Not m_bUnloading Then
    
        cmdStart.Caption = "Start"
        Me.Caption = vbNullString
        tmrFPS.Enabled = False
        
    End If
    
End Sub
 
Private Sub FindTemplate()
    Dim tPos    As tPoint
    
    FillScreenBuffer
    
    tPos = FindImage(m_tScreen, 0, 0, m_tTemplate, m_tMask)
    
    Me.Cls
    
    If tPos.lX = -1 Then
        Me.Print "Not found"
    Else
        Me.Print "X = "; tPos.lX
        Me.Print "Y = "; tPos.lY
    End If
    
End Sub
 
Private Sub UninitializeScreenBuffer()
    
    m_pSADesc = 0
    
    If m_hBufDC Then
        RestoreDC m_hBufDC, -1
        DeleteDC m_hBufDC
    End If
    
    If m_hBuffer Then
        DeleteObject m_hBuffer
    End If
    
End Sub
 
Private Sub InitializeScreenBuffer()
    Dim tBI     As BITMAPINFO
    Dim pBits   As Long
    
    m_tScreen.lWidth = Screen.Width / Screen.TwipsPerPixelX
    m_tScreen.lHeight = Screen.Height / Screen.TwipsPerPixelY
    
    With tBI.bmiHeader
        .biSize = Len(tBI.bmiHeader)
        .biBitCount = 32
        .biHeight = -m_tScreen.lHeight
        .biWidth = m_tScreen.lWidth
        .biPlanes = 1
    End With
    
    m_hBuffer = CreateDIBSection(Me.hDC, tBI, 0, pBits, 0, 0)
    If m_hBuffer = 0 Then
        Err.Raise 7
    End If
    
    m_hBufDC = CreateCompatibleDC(Me.hDC)
    If m_hBufDC = 0 Then
        DeleteObject m_hBuffer: m_hBuffer = 0
        Err.Raise 7
    End If
    
    SaveDC m_hBufDC
    SelectObject m_hBufDC, m_hBuffer
    
    With m_tSaDesc
        .cDims = 1
        .fFeatures = &H11
        .cbElements = 1
        .cElements = m_tScreen.lWidth * m_tScreen.lHeight * 4
        .pvData = pBits
    End With
    
    m_pSADesc = VarPtr(m_tSaDesc)
    
    MoveArray m_tScreen.bData, m_pSADesc
    
End Sub
 
Private Sub FillScreenBuffer()
    Dim hDC As Long
    
    hDC = GetDC(0)
    BitBlt m_hBufDC, 0, 0, m_tScreen.lWidth, m_tScreen.lHeight, hDC, 0, 0, vbSrcCopy
    ReleaseDC 0, hDC
        
End Sub
 
Private Function ImageDescFromFile( _
                 ByRef sFileName As String) As tImageDesc
    Dim cPic    As StdPicture
    Dim tRet    As tImageDesc
    Dim tBI     As BITMAPINFO
    
    Set cPic = LoadPicture(sFileName)
    
    tRet.lWidth = Me.ScaleX(cPic.Width, vbHimetric, vbPixels)
    tRet.lHeight = Me.ScaleY(cPic.Height, vbHimetric, vbPixels)
    
    With tBI.bmiHeader
        .biSize = Len(tBI.bmiHeader)
        .biBitCount = 32
        .biPlanes = 1
        .biWidth = tRet.lWidth
        .biHeight = -tRet.lHeight
    End With
    
    ReDim tRet.bData(tRet.lWidth * tRet.lHeight * 4 - 1)
    
    If GetDIBits(Me.hDC, cPic.handle, 0, tRet.lHeight, tRet.bData(0), tBI, 0) = 0 Then
        Err.Raise 7
    End If
    
    ImageDescFromFile = tRet
    
End Function
 
Private Function FindImage( _
                 ByRef tImage As tImageDesc, _
                 ByVal lStartX As Long, _
                 ByVal lStartY As Long, _
                 ByRef tTemplate As tImageDesc, _
                 ByRef tMask As tImageDesc) As tPoint
    Dim lIndex1 As Long
    Dim lIndex2 As Long
    Dim lIndex3 As Long
    Dim tBPtX   As Long:    Dim tBPtY   As Long
    Dim tSPtX   As Long:    Dim tSPtY   As Long
    Dim tRet    As tPoint
    
    ' // No errors/bounds checking!
    
    tRet.lX = -1: tRet.lY = -1
    lIndex1 = (lStartY * tImage.lWidth + lStartX) * 4
    
    For tBPtY = 0 To tImage.lHeight - lStartY - tTemplate.lHeight - 1
        For tBPtX = 0 To tImage.lWidth - lStartX - tTemplate.lWidth - 1
 
            lIndex2 = 0:    lIndex3 = lIndex1
            
            For tSPtY = 0 To tTemplate.lHeight - 1
                For tSPtX = 0 To tTemplate.lWidth - 1
                
                    If tMask.bData(lIndex2) Then    ' // Test blue channel only
                        If tImage.bData(lIndex3) <> tTemplate.bData(lIndex2) Or _
                            tImage.bData(lIndex3 + 1) <> tTemplate.bData(lIndex2 + 1) Or _
                            tImage.bData(lIndex3 + 2) <> tTemplate.bData(lIndex2 + 2) Then  ' // Ignore alpha
                            GoTo next_col_check
                        End If
                    End If
                    
                    lIndex2 = lIndex2 + 4
                    lIndex3 = lIndex3 + 4
                    
                Next
                
                lIndex3 = lIndex3 + (tImage.lWidth - tTemplate.lWidth) * 4
                
            Next
            
            tRet.lX = tBPtX + lStartX
            tRet.lY = tBPtY + lStartY
            
            GoTo exit_proc
            
next_col_check:
            
            lIndex1 = lIndex1 + 4
            
        Next
        
        lIndex1 = lIndex1 + (lStartX + tTemplate.lWidth) * 4
        
    Next
    
exit_proc:
 
    FindImage = tRet
    
End Function
 
Private Sub Form_Unload( _
            ByRef Cancel As Integer)
            
    m_bUnloading = True
    m_bIsRunning = False
    UninitializeScreenBuffer
    
End Sub
 
Private Sub tmrFPS_Timer()
    Me.Caption = "FPS: " & CStr(m_lFPS)
    m_lFPS = 0
End Sub
Вложения
Тип файла: zip findimg.zip (3.8 Кб, 36 просмотров)
2
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
28.06.2021, 04:58  [ТС]
@ the trick,Thank you, in actual use, the image resolution will be different. It is necessary to set the tolerance, and the similarity check, so a faster algorithm is needed.

Добавлено через 56 минут
The purpose of using a mask map is to ignore the comparison of the surrounding colors, so as to speed up the speed.

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
ReDim zPic(3, W2 - 1, H2 - 1)
  
    I = GetDIBits(mForm.hDC, P2Handle, 0, H2, zPic(0, 0, 0), BI, 0) 'get data
    
    '    Set P2 = Nothing
    '    Set PP.Picture = PP.Image
    '    Dim m1 As Long
    '    m1 = SetDIBits(P1.hDC, PP.Picture.Handle, 0, H2, zPic(0, 0, 0), BI, 0) 'test data
    '    Set PP.Picture = PP.Image
    '    PP.Refresh
  
    'If the colors around the small picture are the same, do not compare the colors of the four corners. Ignore the colors
    If RGB(zPic(2, 0, 0), zPic(1, 0, 0), zPic(0, 0, 0)) = RGB(zPic(2, W2 - 1, 0), zPic(1, W2 - 1, 0), zPic(0, W2 - 1, 0)) And RGB(zPic(2, 0, 0), zPic(1, 0, 0), zPic(0, 0, 0)) = RGB(zPic(2, W2 - 1, H2 - 1), zPic(1, W2 - 1, H2 - 1), zPic(0, W2 - 1, H2 - 1)) And RGB(zPic(2, 0, 0), zPic(1, 0, 0), zPic(0, 0, 0)) = RGB(zPic(2, 0, H2 - 1), zPic(1, 0, H2 - 1), zPic(0, 0, H2 - 1)) Then
  
        R = zPic(2, 0, 0)
        G = zPic(1, 0, 0)
        B = zPic(0, 0, 0)
          
        For J2 = 0 To H2 - 1 'Upper left border
            For I2 = 0 To W2 - 1
 
                If zPic(2, I2, J2) = R Then GoTo NextLine: 'R
                If zPic(1, I2, J2) = G Then GoTo NextLine: 'R
                If zPic(0, I2, J2) = B Then GoTo NextLine: 'R
                xx = I2
                yy = J2
                GoTo aac:
NextLine:
            Next I2
        Next J2
 
aac:
 
        For J2 = H2 - 1 To yy Step -1 'Bottom right corner
            For I2 = W2 - 1 To xx Step -1
 
                If zPic(2, I2, J2) = R Then GoTo NextLine2: 'R
                If zPic(1, I2, J2) = G Then GoTo NextLine2: 'R
                If zPic(0, I2, J2) = B Then GoTo NextLine2: 'R
                y1 = J2
                GoTo aac2:
NextLine2:
            Next I2
        Next J2
 
aac2:
  
        For I2 = W2 - 1 To yy Step -1 'Bottom left
            For J2 = H2 - 1 To xx Step -1
 
                If zPic(2, I2, J2) = R Then GoTo NextLine3: 'R
                If zPic(1, I2, J2) = G Then GoTo NextLine3: 'R
                If zPic(0, I2, J2) = B Then GoTo NextLine3: 'R
                x1 = I2
                GoTo aac3:
NextLine3:
            Next J2
        Next I2
 
aac3:
    Else                                     'Upper right corner
        xx = 0
        yy = 0
        x1 = W2
        y1 = H2
        R = G = B = -1
    End If
0
 Аватар для Argus19
1427 / 444 / 78
Регистрация: 24.09.2017
Сообщений: 2,527
Записей в блоге: 22
28.06.2021, 11:42
I wrote a short cartoon with an entry in the file Picture1.Image and Picture1.Picture. There is no character image in any of these properties.
Вложения
Тип файла: zip 1.ZIP (549.1 Кб, 45 просмотров)
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
29.06.2021, 02:04  [ТС]
Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
Private Function Minimum(ParamArray Vals())
Dim n As Integer, MinVal
On Error Resume Next
    MinVal = Vals(0)
    For n = 1 To UBound(Vals)
        If Vals(n) < MinVal Then MinVal = Vals(n)
    Next n
    Minimum = MinVal
End Function
Private Function Maximum(ParamArray Vals())
Dim n As Integer, MaxVal
On Error Resume Next
    MaxVal = Vals(0)
    For n = 1 To UBound(Vals)
        If Vals(n) > MaxVal Then MaxVal = Vals(n)
    Next n
    Maximum = MaxVal
End Function
 
Private Sub c2hsb(ByVal clr As Long)
Dim MyR As Single, MyG As Single, MyB As Single
Dim Max As Single, Min As Single
Dim MyS As Single
Dim Delta As Single, MyVal As Single
Dim cc As String * 6
Dim r1, g1, b1 As Byte
On Error Resume Next
    cc = Right("000000" + Hex$(clr), 6)
    b1 = Val("&H" + Left(cc, 2))
    g1 = Val("&H" + Mid(cc, 3, 2))
    r1 = Val("&H" + Right(cc, 2))
    MyR = r1 / 255: MyG = g1 / 255: MyB = b1 / 255
    Max = Maximum(MyR, MyG, MyB)
    Min = Minimum(MyR, MyG, MyB)
    hsbB = Int(Max * 100)
    If Max <> 0 Then
        MyS = (Max - Min) / Max * 100
    Else
        MyS = 0
    End If
    hsbS = MyS
    If hsbS = 0 Then
        hsbH = 0
    Else
        Delta = Max - Min
        Select Case Max
        Case MyR
            MyVal = (MyG - MyB) / Delta
        Case MyG
            MyVal = 2 + (MyB - MyR) / Delta
        Case MyB
            MyVal = 4 + (MyR - MyG) / Delta
        End Select
        MyVal = MyVal * 60
        If MyVal < 0 Then MyVal = MyVal + 360
        hsbH = MyVal
    End If
'   Debug.Print "hsb="; hsbH; " "; hsbS; " "; hsbB
End Sub
 
Private Function ColorDistance(ByVal c1 As Long, ByVal c2 As Long) As Long
Dim cd As Long
Dim h1, s1, b1, h2, s2, b2 As Single
On Error Resume Next
    If c1 = -1 Or c2 = -1 Then
        ColorDistance = 1000000
        Exit Function
    End If
    c2hsb (c1)
    h1 = hsbH / 360
    s1 = hsbS
    b1 = hsbB
    c2hsb (c2)
    h2 = hsbH / 360
    s2 = hsbS
    b2 = hsbB
    cd = Abs(h1 - h2)
    cd = cd + Abs(s1 - s2)
    cd = cd + Abs(b1 - b2)
    ColorDistance = cd
End Function
0
 Аватар для Argus19
1427 / 444 / 78
Регистрация: 24.09.2017
Сообщений: 2,527
Записей в блоге: 22
29.06.2021, 15:02
xxdoc, As I understand it, the search is done in a static image with two stacked images?
A Picture object has two properties, Picture1.Picture and Picture1.Image. If you copy an image from Picture2 to Picture1, the copied image will be in Picture1.Image, but it will not be in Picture1.Picture.
Вложения
Тип файла: zip Image copy.zip (138.1 Кб, 19 просмотров)
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
29.06.2021, 16:26  [ТС]
you can set picturebox control autoredraw=true

Добавлено через 11 минут
sorry,i test you demo. i used bitblt or printwindow to copy pic.
0
 Аватар для Argus19
1427 / 444 / 78
Регистрация: 24.09.2017
Сообщений: 2,527
Записей в блоге: 22
29.06.2021, 19:16
Цитата Сообщение от xxdoc Посмотреть сообщение
you can set picturebox control autoredraw=true
If you set Picture1.AutoRedraw = True in example # 10, then the animation will not be visible.
Цитата Сообщение от xxdoc Посмотреть сообщение
i used bitblt or printwindow to copy pic.
bitblt = PaintPicture
0
7 / 7 / 0
Регистрация: 10.07.2015
Сообщений: 69
03.07.2021, 04:46  [ТС]
You are right, but this is not the subject
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
03.07.2021, 04:46
Помогаю со студенческими работами здесь

Как запретить заход одного объекта (picture box) на другой picture box
Создаю платформер на Windows Forms, как запретить заход одного picture box'a на другой?

Можно ли динамически создавать Picture Box внутри другого Picture Box?
Можно ли динамически создавать Picture Box внутри другого Picture Box. Если можно то как? Заранее благодарен

Вписать один Picture control в другой Picture Control на MFC C++
Добрый день, господа! Подскажите пожалуйста как в экранных координатах (проект MFC C++) один Picture Control вписать в другой чтобы меньший...

Splash Screen. После исчезновения splash screen, форма появляется позади всех окон
Реализовал splash screen таким образом: public auth() { Thread t = new Thread(new...

В EntityFramework 7 нету Find. Что можно использовать вместо Find() ?
В EntityFramework 7 нету Find. Что можно использовать вместо Find() ? AspNet 5 Не работает: var i = context.DbSet_ID.Find(id_client);...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
15
Ответ Создать тему
Новые блоги и статьи
Управление камерой с помощью скрипта OrbitControls.js на Three.js: Вращение, зум и панорамирование
8Observer8 05.03.2026
Содержание блога Финальная демка в браузере работает на Desktop и мобильных браузерах. Итоговый код: orbit-controls-threejs-js. zip. Сканируйте QR-код на мобильном. Вращайте камеру одним пальцем,. . .
SDL3 для Web (WebAssembly): Синхронизация спрайтов SDL3 и тел Box2D
8Observer8 04.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-sync-physics-sprites-sdl3-c. zip На первой гифке отладочные линии отключены, а на второй включены:. . .
SDL3 для Web (WebAssembly): Идентификация объектов на Box2D v3 - использование userData и событий коллизий
8Observer8 02.03.2026
Содержание блога Финальная демка в браузере. Итоговый код: finish-collision-events-sdl3-c. zip Сканируйте QR-код на мобильном и вы увидите, что появится джойстик для управления главным героем. . . .
Реалии
Hrethgir 01.03.2026
Нет, я не закончил до сих пор симулятор. Эта задача сложнее. Не получилось уйти в плавсостав, но оно и к лучшему, возможно. Точнее получалось - но сварщиком в палубную команду, а это значит, в моём. . .
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка библиотек: SDL3, Box2D, FreeType, SDL3_ttf, SDL3_mixer и SDL3_image из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru