from future import absolute_import, division, print_function
import os
import random
import numpy as np
from PIL import Image
from skimage.filters import gaussian, sobel
from scipy.interpolate import griddata
import cv2
import torch
from torchvision import transforms
import multiprocessing as mp
from utils import transfer_color
import matplotlib.pyplot as plt
import sys
from tqdm import tqdm
def pil_loader(path):
# print(path)
with open(path, 'rb') as f:
from PIL import Image
with Image.open(f) as img:
return img.convert('RGB')
def read_pfm(file):
with open(file, 'rb') as fh:
fh.readline()
width, height = str(fh.readline().rstrip())[2:-1].split()
fh.readline()
disp = np.fromfile(fh, '<f')
return np.flipud(disp.reshape(int(height), int(width)))
def preprocess(inputs, feed_width, feed_height, disable_normalisation, has_gt, to_tensor, is_train, brightness, contrast, saturation, hue):
if is_train and random.random() > 0.5:
color_aug = transforms.ColorJitter.get_params(
brightness, contrast, saturation, hue)
for key in ['image', 'stereo_image']:
inputs[key] = color_aug(inputs[key])
code
for key in ['image', 'stereo_image']:
if disable_normalisation:
inputs[key] = to_tensor(inputs[key])
else:
inputs[key] = (to_tensor(inputs[key]) - 0.45) / 0.225
if has_gt:
inputs['disparity'] = torch.from_numpy(inputs['disparity']).float()
if inputs.get('mono_disparity') is not None:
inputs['mono_disparity'] = torch.from_numpy(inputs['mono_disparity']).float()
Traceback (most recent call last):
File "/opt/conda/envs/zyh/lib/python3.8/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "datasets/my_dataset_copy_2.py", line 251, in worker
right_image = project_image(np_xs, np_ys, feed_height, process_width,
File "datasets/my_dataset_copy_2.py", line 173, in project_image
pix_locations = np_xs - disp_map
ValueError: operands could not be broadcast together with shapes (1024,788) (1024,768)
if not os.path.isdir(args.input):
targets = [args.input]
else:
targets = [
f for f in os.listdir(args.input) if not os.path.isdir(os.path.join(args.input, f))
]
targets = [os.path.join(args.input, f) for f in targets]
os.makedirs(args.output, exist_ok=True)
for t in targets:
print(f"Processing '{t}'...")
image = cv2.imread(t)
if image is None:
print(f"Could not load '{t}' as an image, skipping...")
continue
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
masks = generator.generate(image)
base = os.path.basename(t)
base = os.path.splitext(base)[0]
save_base = os.path.join(args.output, base)
if output_mode == "binary_mask":
os.makedirs(save_base, exist_ok=False)
write_masks_to_folder(masks, save_base)
else:
save_file = save_base + ".json"
with open(save_file, "w") as f:
json.dump(masks, f)
print("Done!")
Traceback (most recent call last):
File "erode_linecopy.py", line 31, in
f_en = cv2.erode(f, se, mask=mask)
cv2.error: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'erode'
Traceback (most recent call last):
File "erode_linecopy.py", line 37, in
f_en_masked = cv2.bitwise_and(f_en, mask_3channel) # 保留腐蚀部分
cv2.error: OpenCV(4.9.0) /io/opencv/modules/core/src/arithm.cpp:212: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function 'binary_op'
Assistant
The error you encountered indicates that the dimensions of f_en and mask_3channel do not match, which is causing the cv2.bitwise_and() operation to fail. This mismatch can occur when the inputs are not all of the same shape, especially if the mask is not correctly aligned with the color channels of the image.
To resolve this issue, let's ensure that all operations are correctly aligned, and we'll also make sure that the shapes correspond.
Here's the updated code, which includes checks and proper handling to ensure that the sizes align correctly:
Updated Single Image Processing Code
python
import cv2
import numpy as np
# Define input and output file paths
input_image_path = '/home/notebook/data/group/Ruby/langan_datasets/langan/your_image.png' # Replace with your image file
output_image_path = '/home/notebook/data/group/Ruby/langan_datasets/langan/processed/ero_your_image.png' # Output file path
# Read the image
f = cv2.imread(input_image_path)
# Check if the image is loaded successfully
if f is None:
print(f"Error: Could not read image {input_image_path}")
exit()
# Convert to gray image and perform edge detection
gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 100, 200) # Use Canny edge detection
# Detect lines using Hough Transform
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=50, minLineLength=50, maxLineGap=10)
# Create a black mask with the same dimensions as the input image
mask = np.zeros(gray.shape, dtype=np.uint8)
# Draw detected lines on the mask
if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
cv2.line(mask, (x1, y1), (x2, y2), 255, 1) # Draw white lines
# Create a morphological structuring element (circle)
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
# Perform erosion on the image
f_en = cv2.erode(f, se)
# Ensure mask is three channels (BGR)
mask_3channel = cv2.merge([mask, mask, mask]) # Merge mask to 3 channels
# Only keep the eroded parts where the mask is active
f_en_masked = cv2.bitwise_and(f_en, mask_3channel) # Keep eroded parts
f_masked = cv2.bitwise_and(f, cv2.bitwise_not(mask_3channel)) # Keep original non-eroded parts
# Combine the modified and original images
final_result = cv2.add(f_en_masked, f_masked)
# Save the result
cv2.imwrite(output_image_path, final_result)
print(f"Processed and saved: {output_image_path}")
Traceback (most recent call last):
File "erode_line.py", line 38, in
f_en = cv2.erode(f, se, mask=mask)
cv2.error: OpenCV(4.9.0) :-1: error: (-5:Bad argument) in function 'erode'
上述代码报错Traceback (most recent call last):
File "erode_line.py", line 48, in
f_en_masked = cv2.bitwise_and(f_en, mask_3channel) # 保留腐蚀的部分
cv2.error: OpenCV(4.9.0) /io/opencv/modules/core/src/arithm.cpp:212: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function 'binary_op'
你给的代码还是报错,请注意,输入的是三通道的灰度图,所以不需要转换Traceback (most recent call last):
File "erode_line.py", line 49, in
f_en_masked = cv2.bitwise_and(f_en, mask_3channel) # 保留腐蚀的部分
cv2.error: OpenCV(4.9.0) /io/opencv/modules/core/src/arithm.cpp:212: error: (-209:Sizes of input arguments do not match) The operation is neither 'array op array' (where arrays have the same size and type), nor 'array op scalar', nor 'scalar op array' in function 'binary_op'
if not os.path.isdir(args.input):
targets = [args.input]
else:
targets = [
f for f in os.listdir(args.input) if not os.path.isdir(os.path.join(args.input, f))
]
targets = [os.path.join(args.input, f) for f in targets]
for t in targets:
print(f"Processing '{t}'...")
image = cv2.imread(t)
if image is None:
print(f"Could not load '{t}' as an image, skipping...")
continue
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
Added a check to ensure the image is loaded successfully (if f is None:). If the image path is incorrect, the script will exit gracefully with a message.
Creating a Mask:
The code retains the process of drawing the detected lines on a mask.
Three-Channel Mask:
Ensured that the mask is properly converted into a three-channel mask using cv2.merge().
Bitwise Operations:
The cv2.bitwise_and() operations should now work without errors since the sizes should match.
Additional Debugging:
In case of future issues, you can include print statements to check the shapes of f_en, mask_3channel, and final_result.
With these adjustments, the code should fulfill the requirement to only perform erosion on the detected line edges in a single image and prevent size mismatches during the bitwise operations. If any other errors arise or if you have specific requirements, please let me know!