Median filter? Use it to «thin out» bad pixels that appear locally sparse (for some definition of «local»). Then count the remaining bad pixels.
Or convolve with a large-ish 2d kernel (eg flat rectangular window) and decimate to get a number for «how many bad pixels are there inside each eg 16x16 window». Then accumulate the score for each block in a nonlinear fashion (so as to punish really dense blocks).
Im = randi([0 1], 640, 480);
Im_lp = conv2(ones(16), Im);
Im_lp_dec = Im_lp(8:16:end, 8:16:end);
score = sum(Im_lp_dec(:).^2);