Reputation: 11
Working with an image processing project to find all green (128) crosses from multiple images.
Should achieve the following:
The crosses should at least look like this, meaning two crosses can be next to each other. Should count all crosses (inculding copies). The white boxes outside the cross can have various colors
In the left picture below are 2 crosses and in the right you will find four (there are other variants than the two below):
Quite new to all this so thanks in advance, this is what I have to go on:
from PIL import Image
import numpy as np
im = Image.open("testbild.bmp")
M = np.asarray(im)
def antalkors(M):
kors = 0
for i in range(2,M.shape[0]-2):
for j in range(2,M.shape[1]-2):
if M[i][j] == 128 and M[i][j-1] == 128 and M[i][j-2]==128 and M[i][j+1] == 128 and M[i][j+2] == 128 and M[i-1][j] == 128 and M[i-2][j] == 128 and M[i+1][j] == 128 and M[i+2][j] == 128:
kors += 1
return kors
Upvotes: 1
Views: 106
Reputation: 207698
As a first step, I would load the image and make a mask of where the green pixels are so that I just had one channel rather than three to deal with, and to speed up processing:
import cv2
import numpy as np
# Load image as BGR
im = cv2.imread('iejDj.png', cv2.IMREAD_COLOR)
# Now make a single channel image that is 255 where green and black elsewhere:
green = np.all(im==[0,255,0], axis=2) * 255
That looks like this:
Next, make a template along these lines:
template = np.zeros((5,5), np.uint8)
template[2,:] = 255
template[:,2] = 255
That looks like this:
Then follow Christoph's advice and use OpenCV Template Matching.
Upvotes: 1